I have created the following class to sort an array of strings.
public class StringSort {
private String[] hotelNames;
private int arrayLength;
public void sortHotel(String[] hotelArray) {
if (hotelArray.length <= 1) {
return;
}
this.hotelNames = hotelArray;
arrayLength = hotelArray.length;
quicksort(0, arrayLength - 1);
}
private void quicksort(int low, int high) {
int i = low, j = high;
String first = hotelNames[low];
String last = hotelNames[high];
String pivot = hotelNames[low + (high - low) / 2];
while( (first.compareTo(last)) < 0 ) { // first is less than last
while( (hotelNames[i].compareTo(pivot)) < 0 ) { // ith element is < pivot
i++;
}
while( (hotelNames[j].compareTo(pivot)) > 0) { // jth element is > pivot
j--;
}
if ( ( hotelNames[i].compareTo( hotelNames[j] )) <= 0 ) {
swap(i, j);
i++;
j--;
}
//recursive calls
if (low < j) {
quicksort(low, j);
}
if (i < high) {
quicksort(i, high);
}
}
}
private void swap(int i, int j) {
String temp = hotelNames[i];
hotelNames[i] = hotelNames[j];
hotelNames[j] = temp;
}
}
However in my main class (a class to test StringSort), when I do:
StringSort str = new StringSort();
String[] hotel1 = {"zzzz", "wwww", "dddd", "bbbbb", "bbbba", "aaaf", "aaag", "zzz"};
str.sortHotel(hotel1);
And then I have another method that prints out the array. However when it prints out, it outputs the hotel1 array as it is, unchanged. There is no 'sorting' happening, I'm not sure where I've gone wrong.
There are several problems in your implementation of quicksort:
First/last comparison. This code will made your quicksort not do anything as long as first element is less than the last element, regardless of any other order.
while( (first.compareTo(last)) < 0 ) { // first is less than last
Check before swap. This line is unnecessary:
if ( ( hotelNames[i].compareTo( hotelNames[j] )) <= 0 ) {
What you really want to do is see if the i is still less than j and bail out of the loop then. If not, then swap. After you finished with the partitioning loop, then make the recursive call, as long as there are more than two elements in each subarray.
Related
public static void main(String[] args) {
int[] numbers = {20,4,7,6,1,3,9,5};
mergeSort(numbers);
}
private static void mergeSort(int[] inputArray) {
int inputLength = inputArray.length;
System.out.println(inputLength);
if (inputLength < 2)
return;
int midIndex = inputLength / 2;
int[] leftHalf = new int[midIndex];
int[] rightHalf = new int[inputLength - midIndex];
for (int i = 0; i < midIndex; i++) {
leftHalf[i] = inputArray[i];
}
for (int i = midIndex; i < inputLength; i++) {
rightHalf[i - midIndex] = inputArray[i];
}
mergeSort(leftHalf);
mergeSort(rightHalf);
merge(inputArray, leftHalf, rightHalf);
}
private static void merge(int[] inputArray, int[] leftHalf, int[] rightHalf) {
int leftSize = leftHalf.length;
int rightSize = rightHalf.length;
int i = 0, j = 0, k = 0;
while (i < leftSize && j < rightSize) {
if (leftHalf[i] <= rightHalf[i]) {
inputArray[k] = leftHalf[i];
i++;
} else {
inputArray[k] = rightHalf[j];
j++;
}
k++;
}
while (i < leftSize) { //eğer karşılaştırılmayan bir tane kalırsa diye yapılıyor yani
inputArray[k] = leftHalf[i];
i++;
k++;
}
while (j < rightSize) {
inputArray[k] = rightHalf[j];
j++;
k++;
}
}
In the mergeSort part if inputLength < 2 part of the code, we return when the length is less than 2. And last time the inputLength was 1, it becomes 2 and returns to the array [20,4].
This did not make sense to me logically. How does it get back to [20,4] when last we had [20] left?
first of all the code you have shared is flawed in the merge function part, you can find the proper code for Merge sort online, you can refer to
https://www.geeksforgeeks.org/java-program-for-merge-sort/
Now for understanding merge sort you have to understand the concept of stack (Last in First out) & recursion. In recursion the lines after the recursive call wait till the recursive call to the function has not executed completely. So in case of the
1st call Merge sort the length of the array is n and waiting for the complete execution of mergeSort(leftHalf) and mergeSort(rightHalf) both of size (n/2).
now for both the mergeSort(leftHalf) and mergeSort(rightHalf)
there will be sub left part and sub right part and this will continue till the size of the array becomes <2 and the remaining part will wait.
and after the successful execution of the smallest part it will return to the previous part from where this part was called. By this eventually this will return to the place where the function was called first.
And in case of your code both the smaller arrays are merged into the larger array so the data of the left and right sub array aren't lost.
I am supposed to write a version of the selection sort algorithm that moves the smallest number to the front of the array while simultaneously moving the largest number to the end of the array. I understand that it is basically working from both ends in so there are two sorted sub arrays, however my code seems to misplace the last number in the array. My code:
public static void dualSelectionSort(int[]a) {
for(int i=0; i<a.length-1;i++) {
int min=i;
int max=(a.length-1)-i;
for (int j=i+1;j<a.length-i;j++) {
if(a[j]<a[min]) {
min=j;
}
if(a[j]>a[max]) {
max=j;
}
}
int temp1=a[min];
int temp2=a[max];
a[min]=a[i];
a[max]=a[(a.length-1)-i];
a[i]=temp1;
a[(a.length-1)-i]=temp2;
}
}
If given the input [5,4,3,2,1], it outputs [1,2,5,3,4] instead of [1,2,3,4,5].
What am I missing?
The problem is in the inner loop.
It is starting from i+1.
So the code for comparing max is actually comparing a[1] to a[4].
you can change it as
for (int j=i;j<a.length-i;j++)
Also as you can read in comment there can be a case where with the above change the code will still not work.
This will happen because i == max and so the existing swap approach will not work.
For example:
assume array =[6,4,5],inner loop max =0,min=1.Existing swap will make it [4,6,6].
Hence,swap should be handled differently.
if(i==max) {
swap(a,max,a.length-1-i);
swap(a,min,i);
}else {
swap(a,min,i);
swap(a,max,(a.length-1)-i);
}
The complete code is as below:
public static void dualSelectionSort(int[]a) {
for(int i=0; i<a.length-1;i++) {
int min=i;
int max=(a.length-1)-i;
for (int j=i;j<a.length-i;j++) {
if(a[j]<a[min]) {
min=j;
}
if(a[j]>a[max]) {
max=j;
}
}
if(i==max) {
swap(a,max,a.length-1-i);
swap(a,min,i);
}else {
swap(a,min,i);
swap(a,max,(a.length-1)-i);
}
}
}
public static void swap(int[] a,int i,int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
In each iteration of the outer loop, you start with the first index (i) as the initial minimum index and the last index (a.length-1-i) as the initial maximum index. Then you compare both of these indices to all the indices in the range i+1 to a.length-i-1. But if the first index (i) actually contain the max value, you never compare it to a[max], so a[max] will never contain the correct value in the end of the inner loop.
Here's a suggested fix:
public static void dualSelectionSort(int[]a) {
for(int i = 0; i < a.length - i - 1; i++) {
if (a[i] > a[(a.length - 1) - i]) {
int temp = a[i];
a[i] = a[(a.length - 1) - i];
a[(a.length - 1) - i] = temp;
}
int min = i;
int max = (a.length - 1) - i;
for (int j = i + 1; j < (a.length -1 ) - i; j++) {
if(a[j] < a[min]) {
min = j;
}
if(a[j] > a[max]) {
max = j;
}
}
int temp1 = a[min];
int temp2 = a[max];
a[min] = a[i];
a[max] = a[(a.length - 1) - i];
a[i] = temp1;
a[(a.length - 1) - i] = temp2;
}
}
The three things I changed:
The outer loop can end much sooner than you end it - once i >= a.length-i-1 - since in each iteration you find the minimum and maximum value, so you reduce your remaining unsorted array by 2.
When initializing the min and max indices, make sure min index actually contains a value smaller the max index. If a[i] > a[(a.length-1)-i], swap them before setting min to i and max to (a.length-1)-i.
The inner loop should iterate j from i+1 to (a.length-1)-i-1.
I have a problem I can't -quite- wrap my head around. I'm racing quicksort vs heapsort on one million integers. Each of the sorting algorithms divides the list into 32 threaded sub-sections and then sorts those, finally merging each sorted subsection back into a coherent whole (using more threads).
Rather than sorting the whole sub-array using quicksort and then pushing the whole thing out to the mergers, I'm trying to find a way to find the min value(s) using quicksort and push that before the whole section has been sorted. Since I don't actually have enough cores to concurrently run all my threads I expect the performance impact to be negligible, but I'd like to test that theory.
Time on my machine with 4 cores is about 14 seconds plus or minus two for both heapsort and quicksort. Speed seems to depend on which algorithm I run first, even though I'm shuffling after the sort.
Here's my quicksort code right now:
//code borrowed from http://stackoverflow.com/questions/19124752/non-
//recursive-quicksort
public synchronized void qSort(PipedOutputStream pout, int start, int sz) {
Deque<int[]> stack = new ArrayDeque<int[]>();
int first = start;
int last = start + sz - 1;
if(first >= arr.length || last >= arr.length){
System.out.printf("\nSorting error: parameters out of bounds! Start %d, end %d \n", start, last);
return;
}
stack.push(new int[] {first, last});
while(!stack.isEmpty()) {
qsortStep(arr, stack);
}
try { out = new ObjectOutputStream ( pout ); }
catch (IOException e ) { e.printStackTrace(); }
while ( size >= 1 ) {
try {
// System.out.printf("sort is writing %d to pipe.\n", v );
out.writeObject( arr[start] );
out.flush( );
start++; size--;
} catch(IOException e ) { e.printStackTrace(); }
}
}
private synchronized void qsortStep(T[] list, Deque<int[]> stack) {
if(stack.isEmpty())
return;
int temp[] = stack.pop();
int first = temp[0];
int last = temp[1];
int boundLo = first;
int boundHi = last;
//Pivot can be optimized to median of quintiles to mitigate O(n^2) on sorted arrays.
int pivot = last;
/*int sz = last - first;
int pivots[] = {first, first+sz/5, first+2*sz/5, first+4*sz/5, last};
for(int i = 0; i < 5; i++)
for(int j = 4; j > i; j--)
if(arr[pivots[i]].compareTo(arr[pivots[j]]) > 0)
swap(pivots, i, j);*/
pivot = last;
while(first < last) {
//possible opportunity here for early min
if(list[first].compareTo(list[pivot]) >= 0) {
last--;
if(first != last)
swap(list, first, last);
swap(list, last, pivot);
pivot--;
}
else first++;
}
if(boundLo < (pivot - 1))
stack.add(new int[] {boundLo, pivot - 1});
if(boundHi > (pivot + 1))
stack.add(new int[] {pivot + 1, boundHi});
}
I am coding the non-recursive merge sort algorithm in Java
I have to make sure if this method works as a non recursive as well as the space complexity should be O(N)
Instruction I got: You can use O(N) space (in addition to the input array) and your algorithm should have the same running time as recursive merge sort.
here's my code.
I want to make sure the recursiveness as well as the O(N) space
If there's a better way, please let me know.
private static void merge(Integer[] a, Integer[] tmpArray, int leftPos, int rightPos, int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while(leftPos <= leftEnd && rightPos <= rightEnd) {
if( a[leftPos] <= a[rightPos ]) {
tmpArray[tmpPos++] = a[leftPos++];
} else {
tmpArray[tmpPos++] = a[rightPos++];
}
}
while( leftPos <= leftEnd ) { // Copy rest of first half
tmpArray[tmpPos++] = a[leftPos++];
}
while( rightPos <= rightEnd ) { // Copy rest of right half
tmpArray[tmpPos++] = a[rightPos++];
}
// Copy tmpArray back
for( int i = 0; i < numElements; i++, rightEnd-- ) {
a[rightEnd] = tmpArray[rightEnd];
}
}
public static void mergeSortB(Integer[] inputArray) {
Integer[] tempArray = new Integer[inputArray.length];
for(int i = 1; i<inputArray.length; i=i*2) {
for(int j=i; j<inputArray.length; j=j+i*2) {
int k = j+i-1;
if(inputArray.length<j + i) {
k = inputArray.length -1;
}
//call the merge method(non recursive)
merge(inputArray, tempArray, j-i,j, k);
}
}
}
Your code looks okay. Although, you can create a test (and debug if necessary) to make sure your code is working.
But Merge Sort has Big(O)== NlogN, not N.
I'm a programming student and rather than post the whole assignment I'll just ask for help solving what I've tried for hours now to understand. I'm tasked with sorting an array of strings using the quicksort method. Everything else I've been tasked with as part of this problem is fine but when I tested the sorting method by printing out the String Array, it's completely jumbled up without any seeming rhyme or reason. Please help me pinpoint the error in my code, or the several glaring errors I've overlooked. The array of strings provided is this list of 65 names: http://pastebin.com/jRrgeV1E and the method's code is below:
private static void quickSort(String[] a, int start, int end)
{
// index for the "left-to-right scan"
int i = start;
// index for the "right-to-left scan"
int j = end;
// only examine arrays of 2 or more elements.
if (j - i >= 1)
{
// The pivot point of the sort method is arbitrarily set to the first element int the array.
String pivot = a[i];
// only scan between the two indexes, until they meet.
while (j > i)
{
// from the left, if the current element is lexicographically less than the (original)
// first element in the String array, move on. Stop advancing the counter when we reach
// the right or an element that is lexicographically greater than the pivot String.
while (a[i].compareTo(pivot) < 0 && i <= end && j > i){
i++;
}
// from the right, if the current element is lexicographically greater than the (original)
// first element in the String array, move on. Stop advancing the counter when we reach
// the left or an element that is lexicographically less than the pivot String.
while (a[j].compareTo(pivot) > 0 && j >= start && j >= i){
j--;
}
// check the two elements in the center, the last comparison before the scans cross.
if (j > i)
swap(a, i, j);
}
// At this point, the two scans have crossed each other in the center of the array and stop.
// The left partition and right partition contain the right groups of numbers but are not
// sorted themselves. The following recursive code sorts the left and right partitions.
// Swap the pivot point with the last element of the left partition.
swap(a, start, j);
// sort left partition
quickSort(a, start, j - 1);
// sort right partition
quickSort(a, j + 1, end);
}
}
/**
* This method facilitates the quickSort method's need to swap two elements, Towers of Hanoi style.
*/
private static void swap(String[] a, int i, int j)
{
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
Ok, i was mistaken that it would work and found your tiny mistake.
Take a look at wikipedias pseudo code
You will notice that your conditions in the while loop are causing the error
if you change (a[i].compareTo(pivot) < 0 && i <= end && j > i) and (a[j].compareTo(pivot) > 0 && j >= start && j >= i) to
(a[i].compareTo(pivot) <= 0 && i < end && j > i) and (a[j].compareTo(pivot) >= 0 && j > start && j >= i).
Thought this would help for those who seek for a string sorting algorithm based on quick sorting method.
public class StringQuickSort {
String names[];
int length;
public static void main(String[] args) {
StringQuickSort sorter = new StringQuickSort();
String words[] = {"zz", "aa", "cc", "hh", "bb", "ee", "ll"}; // the strings need to be sorted are put inside this array
sorter.sort(words);
for (String i : words) {
System.out.print(i);
System.out.print(" ");
}
}
void sort(String array[]) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
//call quickSort recursively
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j) {
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
}