Qick Sort
Qick Sort
1. An array is divided into subarrays by selecting a pivot element (element selected from the
array).
While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side of
the pivot.
2. The left and right subarrays are also divided using the same approach. This process continues
until each subarray contains a single element.
3. At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.
Put all the smaller elements on the left and greater on the right of pivot element
Here's how we rearrange the array:
1. A pointer is fixed at the pivot element. The pivot element is compared with the elements
beginning from the first index.
Comparison of pivot element with element beginning from the first index
2. If the element is greater than the pivot element, a second pointer is set for that element.
If the element is
greater than the pivot element, a second pointer is set for that element.
3. Now, pivot is compared with other elements. If an element smaller than the pivot element is
reached, the smaller element is swapped with the greater element found earlier.
The process is repeated to set the next greater element as the second pointer.
3. Divide Subarrays
Pivot elements are again chosen for the left and the right sub-parts separately. And, step 2 is
repeated.
Select pivot element of in each half and put at correct place using recursion
// Quick sort in C
#include <stdio.h>
int t = *a;
*a = *b;
*b = t;
i++;
swap(&array[i], &array[j]);
return (i + 1);
quickSort(array, pi + 1, high);
printf("\n");
// main function
int main() {
printf("Unsorted Array\n");
printArray(data, n);
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: \n");
printArray(data, n);