java - Whats wrong with my QuickSort implementation? -
java - Whats wrong with my QuickSort implementation? -
class partitionit { public static void partitionit(int[] a, int l, int r, int pivot) { int i,j; = j = l+1; while(j<= r) { if(a[j] <= a[pivot]) { swap(a,j,i); i++; } j++; } swap(a,pivot,--i); } public static void swap(int[] a, int j, int i) { int temp = a[j]; a[j] = a[i]; a[i] = temp; } public static void displayarray(int[] a) { for(int i:a) system.out.print(i+" "); system.out.println(); } public static void quicksort(int[] a, int l, int r) { if(r <= l) return; int pivot = getpivot(a,l,r); partitionit(a,l,r,pivot); quicksort(a,l,pivot); quicksort(a,pivot+1,r); } public static int getpivot(int[] a,int l,int r) { homecoming l; } public static void main(string[] args) { int[] = {3,2,8,5,1,4,7,6}; int[] b = {1,2,3,4,5,6,7,8,9,0}; int[] c = {5,4,2,4,7,6,5,3,2,1,10}; displayarray(a); system.out.println("after parititon pivot 3"); quicksort(a,0,a.length-1); displayarray(a); system.out.println(); displayarray(b); system.out.println("after parititon pivot 1"); quicksort(b,0,b.length-1); displayarray(b); system.out.println(); displayarray(c); system.out.println("after parititon pivot 5"); quicksort(c,0,c.length-1); displayarray(c); system.out.println(); }
}
3 2 8 5 1 4 7 6 after parititon pivot 3 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 9 0 after parititon pivot 1 0 1 2 3 4 5 6 7 8 9 5 4 2 4 7 6 5 3 2 1 10 after parititon pivot 5 1 2 2 4 3 4 5 5 6 7 10
it not sorting in lastly case.
can help here. m stuck long.
thanks in advance!
at snippet:
if(a[j] <= a[pivot]) { swap(a,j,i); i++; }
the '<=' should '<'.
while sequence sorted 1 2 2 4 3 4 5 5 7 6 10,the pivot '4'(the left one),while compare 4 <= 4,i++, cause swap(a,pivot,--i) alter location of '4'(the right 1 ) '4'(the left one),rather alter '3' '4'.
java quicksort
Comments
Post a Comment