Quick sort algorithm

Partitioning

Operation:

   
   
Comparisons done:
Exchanges done:
Legend:
12 - "boundary" element
12 - elements belonging to the first part of the array
12 - wrong element that doesn't allow us to go down/up
24 - elements belonging to the second part of the array
29 - elements being compared
10 - elements being exchanged
12 - yet unchecked elements

Quick sort

 
    
Comparisons done:
Exchanges done:
Legend:
12 - "boundary" element
12 - elements belonging to the first part of the array
7 - elements of the currently being sorted sub-array
24 - elements belonging to the second part of the array

The main idea of the quick sort algorithm is to partition an array into two censecuitive sub-arrays in such a way that the largest elementof the first one was less or at most equal to the smallest element of the second one. If we know how to do this partitioning, then all we need to do is to sort both sub-arrays. We don't even need to merge them, beacuse of the way we partitioned the original array.

If we assume that we have a funtion named partition() that takes an array, the first and the last index of it and returns the index of the element which is located on the boundary of these sub-arrays, then we can implement the quick-sort() function very easy:

void quick_sort(int data[], int first, int last)
{
   int middle = partition(data, first, last);
   quick_sort(data, first, middle-1);
   quick-sort(data, middle+1, last)
}
Please note that this quick sort function is not complete yet because we did not insert any checking if we need to continue partitioning and sorting or not. Shortly speaking, we need to check the size of the array before the partitioning.