Open In App

Quick Sort in C

Last Updated : 02 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Pick a Card: Randomly choose any card from the pile. Call this card “pivot.”
  2. 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.
  3. Sort the Piles: Now, repeat the same process of dividing each of the two piles until each pile only has one card left.
  4. 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:

  1. partition() Function
  2. 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()

  1. Initially, the low points to the first index and the high points to the last index.
  2. Get the index(where the pivot should be placed after sorting) using a partition() function call it partition index.
  3. 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()

  1. First select the pivot.
  2. Take two-pointers i and j. The i pointer points to low and the j points to high.
  3. 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.
  4. 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).
  5. 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.

Quick-Sort-Algorithm

Example of Quick Sort

C Program for Quick Sort

Below is the Implementation of Quick Sort in C.

C




// C program to implement Quick Sort Algorithm
#include <stdio.h>
  
// Function to swap two elements
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
  
// Partition function
int partition(int arr[], int low, int high)
{
  
    // initialize pivot to be the first element
    int pivot = arr[low];
    int i = low;
    int j = high;
  
    while (i < j) {
  
        // condition 1: find the first element greater than
        // the pivot (from starting)
        while (arr[i] <= pivot && i <= high - 1) {
            i++;
        }
  
        // condition 2: find the first element smaller than
        // the pivot (from last)
        while (arr[j] > pivot && j >= low + 1) {
            j--;
        }
        if (i < j) {
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[low], &arr[j]);
    return j;
}
  
// QuickSort function
void quickSort(int arr[], int low, int high)
{
    if (low < high) {
  
        // call Partition function to find Partition Index
        int partitionIndex = partition(arr, low, high);
  
        // Recursively call quickSort() for left and right
        // half based on partition Index
        quickSort(arr, low, partitionIndex - 1);
        quickSort(arr, partitionIndex + 1, high);
    }
}
  
// driver code
int main()
{
    int arr[] = { 19, 17, 15, 12, 16, 18, 4, 11, 13 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // printing the original array
    printf("Original array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
  
    // calling quickSort() to sort the given array
    quickSort(arr, 0, n - 1);
  
    // printing the sorted array
    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 –

  1. Quick sort has the best time complexity compared to other sorting algorithms.
  2. It uses Divide and Conquer Strategy which makes the algorithm easier to understand and solve problems.
  3. Suitable for large datasets or highly structured data.

Disadvantages of Quick Sort Algorithm

Following are the disadvantages of Quick Sort Algorithm –

  1. The worst-case time complexity of Quick Sort is O(n2) if the pivot chosen leads to bad partitioning of an array.
  2. 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).
  3. Not suitable for small datasets.
  4. 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads