This is code that I came across implementing the quick sort algorithm. Can you please explain how the recursion works here?
void quickSort(int arr[], int left, int right)
{
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];
/* partition */
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--;
}
}
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
And please note, this is not homework.
Not sure what you mean with “explain how the recursion is working”. But here you go:
The function you posted takes an array of ints and two indexes. It will not sort the whole array, but only the part of it between the two indexes, ignoring anything that is outside them. This means the same function can sort the whole array if you pass the first and last indexes, or just a sub array if you pass a
leftvalue that is not the index of the first element of the array and/or arightvalue that is not the index of the last element.The sorting algorithm is the well known quicksort. The as pivot it uses the central element (it could as well have used any other element). It partitions the array into the
less than (or equal to) pivotsubarray and thegreater than (or equal to) pivotsubarray, leaving an element equal to the pivot between the two partitions.Then it recursively calls itself to sort the two partitions, but only does it if it is necessary (hence the ifs before the recursive calls).
The implementation works, but is sub-optimal in many ways, and could be improved.
Here are some possible improvements: