I am trying to understand the quicksort mechanism but so far I can't figure it out. According to wikipedia, the steps are :
1. Pick an element, called a pivot, from the list.
2. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
3. Recursively apply the above steps to the sub-list of elements with smaller values and separately the sub-list of elements with greater values.
And this is the code:
int partition(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
return i;
}
void quickSort(int arr[], int left, int right) {
int index = partition(arr, left, right);
if (left < index - 1)
quickSort(arr, left, index - 1);
if (index < right)
quickSort(arr, index, right);
}
All is somehow clear to me except one thing. Why is the partition function returning i
and not j
?
return j;
instead ofreturn i;
, for the array{3,2,4,1}
the program crashes – TeoquickSort
function you have there expectspartition
to return the index of the first element of the second partition. Changing it to expect the index of the last element would be a pretty trivial change. – Mooing DuckquickSort
that is not returning the index of the first element in the second partition? – Teo