Quick Sort in C
Last Updated :
02 Jan, 2024
QuickSort is one of the best sorting algorithms developed by Tony Hoare in 1960 to sort the array. It follows the divide-and-conquer rule like Merge Sort but unlike Merge Sort, this algorithm does not use any extra space for sorting (though it uses an auxiliary stack space).
The basic idea behind QuickSort is to select a “pivot” element from the array and partition the other elements into two sub-arrays according to whether they are less than or greater than the pivot.
Real-life Example Based on Quick Sort
Imagine you have a pile of cards and you want to arrange them in order from smallest to largest.
Here’s how you can do it:
- Pick a Card: Randomly choose any card from the pile. Call this card “pivot.”
- Divide the Pile: Separate the remaining cards into two piles – one pile having cards that are smaller than the pivot and another with cards larger than the pivot.
- Sort the Piles: Now, repeat the same process of dividing each of the two piles until each pile only has one card left.
- Combine Sorted Piles: When all the sub piles are sorted, put them together in order such that the smallest is on the left and the largest on the right.
Hence, a deck of cards is sorted by repeatedly dividing and conquering the task.
Quick Sort Algorithm
This algorithm basically requires implementation of two functions:
- partition() Function
- quickSort() Function
1. quickSort() Function
The quickSort() function accepts three parameters:
- arr[]: array of Integer of Size n.
- low: points to the first index.
- high: points to the last index.
Working of quickSort()
- Initially, the low points to the first index and the high points to the last index.
- Get the index(where the pivot should be placed after sorting) using a partition() function call it partition index.
- Call the function quickSort() for the left and the right subarray recursively. i.e quickSort(arr, low, partitionIndex – 1) and quickSort(arr, partitioning + 1, high) do this while(low<high)
2. partition() Function
The partition() function accepts three parameters:
- arr[]: array of integer.
- low: points to the starting index.
- high: points to ending index.
Working of partition()
- First select the pivot.
- Take two-pointers i and j. The i pointer points to low and the j points to high.
- Pointer i will move forward and find the first element greater than the pivot. Similarly, the pointer j will move backward and find the first element smaller than the pivot.
- Once we find such elements i.e. arr[i] > pivot and arr[j] < pivot, and i < j, we will swap arr[i] and arr[j]. Continue steps 3 and step 4, until j becomes smaller than I (J crosses I).
- Finally, we will swap the pivot element(i.e. arr[low]) with arr[j] and will return the index j i.e. the partition index.
Note: Here add some checks like i <= high-1 and j >= low+1. Because it might happen that i is standing at high and trying to proceed or j is standing at low and trying to exceed.
Example of Quick Sort
C Program for Quick Sort
Below is the Implementation of Quick Sort in C.
C
#include <stdio.h>
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition( int arr[], int low, int high)
{
int pivot = arr[low];
int i = low;
int j = high;
while (i < j) {
while (arr[i] <= pivot && i <= high - 1) {
i++;
}
while (arr[j] > pivot && j >= low + 1) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
}
swap(&arr[low], &arr[j]);
return j;
}
void quickSort( int arr[], int low, int high)
{
if (low < high) {
int partitionIndex = partition(arr, low, high);
quickSort(arr, low, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, high);
}
}
int main()
{
int arr[] = { 19, 17, 15, 12, 16, 18, 4, 11, 13 };
int n = sizeof (arr) / sizeof (arr[0]);
printf ( "Original array: " );
for ( int i = 0; i < n; i++) {
printf ( "%d " , arr[i]);
}
quickSort(arr, 0, n - 1);
printf ( "\nSorted array: " );
for ( int i = 0; i < n; i++) {
printf ( "%d " , arr[i]);
}
return 0;
}
|
Output
Original array: 19 17 15 12 16 18 4 11 13
Sorted array: 4 11 12 13 15 16 17 18 19
Time Complexity: O(n*logn), where n = size of the array.
Space Complexity: O(1) + O(n) (Considering auxiliary stack space).
For Detailed Complexity Analysis Refer Time and Space Complexity Analysis of Quick Sort
How to Choose Pivot in Quick Sort Algorithm?
pivot is any chosen element from the given array. It serves as a point that is used for partitioning the array into two subarray (right half and left half).
Common strategies used to choose the pivot are:
- First Element: Choosing the first element of the array as the pivot.
- Last Element: Choosing the last element of the array as the pivot.
- Median of the Array: Calculating the median of the array (the middle element when the array is sorted) and using it as the pivot.
- Random Element: Randomly selecting any element from the array to be the pivot.
The Selection of a pivot can impact the efficiency of the Quick sort algorithm.
Advantages of Quick Sort Algorithm
Following are the main advantages of the Quick Sort Algorithm –
- Quick sort has the best time complexity compared to other sorting algorithms.
- It uses Divide and Conquer Strategy which makes the algorithm easier to understand and solve problems.
- Suitable for large datasets or highly structured data.
Disadvantages of Quick Sort Algorithm
Following are the disadvantages of Quick Sort Algorithm –
- The worst-case time complexity of Quick Sort is O(n2) if the pivot chosen leads to bad partitioning of an array.
- Quick Sort is not stable because in the Quick Sort Algorithm swapping of elements is done according to the pivot’s position (without even considering their original positions).
- Not suitable for small datasets.
- Difficult to implement because it requires careful selection of pivot to get the optimal results.
FAQs on Quick Sort in C
Q1. What is Quick Sort?
Answer:
Quick sort is one of the best sorting algorithm. It works on the Divide and Conquer Strategy as It selects a pivot element and partitions the given array into two subarrays based on partition index, the left half having elements less than the pivot and the right half having elements greater than the pivot.
Q2. What is the time complexity of Quick Sort?
Answer:
- The average case Time Complexity of Quick sort is O(n log n) (n is a number of elements in an array).
- Worse case Time Complexity of Quick sort is O(n2) it happens in rare conditions when the pivot is poorly selected.
Q3. Is Quick Sort a Stable or Unstable sorting algorithm?
Answer:
No, Quick Sort is not stable because in the Quick Sort Algorithm swapping of elements is done according to the pivot’s position (without even considering their original positions).
Q4. Does Quick Sort use Extra SpaceSort?
Answer:
No, Quick Sort does not use Extra Space because Quick Sort is an in-place sorting algorithm. However, it uses a recursive approach that may consume the stack space.
Q5. How does Quick Sort work?
Answer:
Quick Sort works on the Divide and Conquer Strategy by recursively partitioning the given array into right and left halves and sorting each partition using a pivot by rearranging the array elements in such a manner that elements that are smaller than the pivot are on the left, and the elements which are greater than the pivot is on the right. Keep repeating this process for each partition to get the sorted array.
Q6. How to Choose Pivot in Quicksort?
Answer:
The pivot in Quick Sort can be chosen in various ways like Selecting the first element as a Pivot, the last element, the median of three elements, or a random element. The Selection of the pivot element affects the efficiency of the algorithm.
Share your thoughts in the comments
Please Login to comment...