I am trying to implement QuickSort in java but Could not get output? -
i trying implement quicksort taking last element pivot. unable produce valid output.
also change needs done in order make randomized? coding in java.
public class quicksortdemo { public static void quicksort(int a[], int temp[], int left, int right) { int q, i; //why u need check base case if (left < right) { q = partition(a, temp, left, right); quicksort(a, temp, left, q - 1); quicksort(a, temp, q + 1, right); (i = 0; < a.length; i++) { system.out.println(a[i]); } } } public static int partition(int a[], int temp[], int left, int right) { int x, i, j; x = a[right]; = left - 1; (j = left; j <= right - 1; j++) { if (a[j] <= x) { = + 1; a[i] = a[j]; } } a[i + 1] = a[right]; return + 1; } public static void main(string s[]) { int ar[] = {6, 3, 2, 5, 4}; int p[] = new int[ar.length]; quicksort(ar, p, 0, ar.length - 1); } } //end class quicksortdemo
outputshown
2 2 4 5 4 2 2 4 4 4 2 2 4 4 4
as mentioned in comments, there errors in partition method. when implementing quicksort want swap elements in array , not overwrite ones in front. lost.
furthermore, code starts on left , swappes every element less or equal pivot. these unnecessary operations if element in correct part of array.
it better search element greater pivot left. then, search element less pivot right, swap , continue until necessary elements have been swapped.
the standard implementation (that know) this
public static int partition(int a[], int left, int right) { int pivot, i, j; pivot = a[right]; = left; j = right - 1; { // search element greater pivot left, remember position while ( a[i] <= pivot && < right ) i++; // search element less pivot right, remember positon while ( a[j] >= pivot && j > left ) j--; // if elements in wrong part of array => swap if ( < j ) swap( a, i, j ); // continue until whole (sub)array has been checked } while ( j > ); // put pivot element @ final position if possible if ( a[i] > pivot ) swap ( a, i, right ); // return border / position of pivot element return i; }
the swap usual
public static void swap(int[] a, int first, int second) { int temp = a[first]; a[first] = a[second]; a[second] = temp; }
also note, there no need use temp
within code. code declares in signatures never uses it.
Comments
Post a Comment