java - Quicksort partitioning -
i have following array:
int[] arr = { 19, 4, 2, 3, 9, 2, 10, 2, 7, 12, 5, 16, 8, 3, 11, 14, 0, 5 };
and use quicksort's partitioning partition array pivot element 7:
public static void partition(int[] arr, int low, int high) { int pivot = arr[low + (high - low) / 2]; int = low; int j = high; while (i <= j) { // if current value left list smaller pivot // element next element left list while (arr[i] < pivot) { i++; } // if current value right list larger pivot // element next element right list while (arr[j] > pivot) { j--; } // if have found values in left list larger // pivot element , if have found value in right list // smaller pivot element exchange // values. // done can increase , j if (i <= j) { swap(arr, i, j); i++; j--; } } }
i confused outcome:
5 4 2 3 0 2 3 2 5 12 7 16 8 10 11 14 9 19
i thought every element <= pivot (7) must left , every element > pivot element must on right. why 12 left 7 ?
this implementation cannot guarantee expect. following (provided change arr[i] <= pivot
, achintya jha suggested, otherwise can't guarantee that):
for every pair of values a, b
a <= pivot < b
, guaranteed a
left of b
in end. however, don't guarantee anything exact position of pivot
in final array (only it's left of values larger).
Comments
Post a Comment