I am trying to implement the quicksort algorithm using Java. I have created my partition function as follows:
int [] quickPartition(int[] array, int low, int high){
int pivot = array[low], end_mark = high, start_mark = 1, temp;
while (start_mark != end_mark) {
if (array[start_mark] > pivot) {
while (end_mark != start_mark) {
if (array[end_mark] < pivot) {
temp = array[end_mark];
array[end_mark] = array[start_mark];
array[start_mark] = temp;
break;
}
end_mark--;
}
}
start_mark++;
}
return array;
}
array[low] is my pivot, end_mark is the last element of the array and start_mark is the first element after pivot
The first while loop loops from the start towards the end looking for the next number larger than the pivot. When found, the second loop starts from the end of the array towards the start looking for the next number smaller than the pivot. If both of these conditions are satisfied, swapping occurs. However, if the both the looping indices(startindex and endindex) meet, the while loops exit.
Sample array: [54, 26, 93, 17, 77, 90, 31, 44, 55, 20]
Returned: [54, 26, 20, 17, 44, 31, 90, 77, 55, 93]
As you can see, the relevant elements have been partitioned. However, the last step involves swapping the pivot(54) and (31), So that all elements greater than 54 are on the right and those less than 54 are on the left. How do you swap 31 and 54 yet at this point(where start_index == end_index) the while loop has already stopped? Take note that if you swap outside the while loops the value 31 will be lost.