Quick Sort Algorithm Explained Simply
Quick Sort is a divide-and-conquer algorithm for sorting. It works by selecting a "pivot"
element from the array and then dividing the array into two parts:
● Elements less than the pivot.
● Elements greater than the pivot.
The process is repeated recursively for the two sub-arrays until the entire array is sorted.
Steps of Quick Sort
1. Choose a Pivot: Pick an element as the pivot (can be the first, last, or any random
element).
2. Partition: Rearrange the array so that all elements less than the pivot go to its left,
and all greater elements go to its right.
3. Recursively Sort: Apply the same logic to the left and right sub-arrays.
Key Points
● The algorithm is in-place, meaning it requires no extra storage.
● The average time complexity is O(nlogn)O(n \log n), but in the worst case (poor pivot
selection), it becomes O(n2)O(n^2).
C Code for Quick Sort with Explanation
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function: places the pivot at the correct position
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choosing the last element as the pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
// Place the pivot at the right position
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
// Quick Sort function
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high); // Partition index
// Recursively sort elements before and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Main function to test Quick Sort
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Explanation of Code
1. partition Function:
○ Selects the pivot (last element).
○ Rearranges the array such that all smaller elements are left of the pivot and
larger ones are on the right.
○ Returns the index of the pivot after rearrangement.
2. quickSort Function:
○Recursively calls itself for the left and right partitions until the entire array is
sorted.
3. swap Function:
○ Used to exchange elements in the array during partitioning.
4. Input and Output:
○ Input: {10, 7, 8, 9, 1, 5}
○ Output: {1, 5, 7, 8, 9, 10}
Example Walkthrough
For array {10, 7, 8, 9, 1, 5}:
1. Pivot = 5
2. Partition results: {1, 5, 8, 9, 10, 7} (pivot 5 placed in position).
3. Repeat for sub-arrays {1} and {8, 9, 10, 7}.
4. Final sorted array: {1, 5, 7, 8, 9, 10}.