• C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++

Open In App

Last Updated : 02 Jan, 2024

Improve

Improve

Like Article

Like

Save

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 in C - GeeksforGeeks (1)

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.



M

manshisharma13

Improve

Next Article

Iterative Quick Sort

Please Login to comment...

Similar Reads

Quick Sort vs Merge Sort Quick sort is an internal algorithm which is based on divide and conquer strategy. In this: The array of elements is divided into parts repeatedly until it is not possible to divide it further.It is also known as “partition exchange sort”.It uses a key element (pivot) for partitioning the elements.One left partition contains all those elements that 4 min read Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists? Why is Quick Sort preferred for arrays? Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for array. Iterative Quick Sort for arrays. Recursive Merge Sort for arrays Iterative Merge Sort for arrays Quick Sort in its general form is an in-place sort (i.e. it doesn't require any extra stor 5 min read Bucket Sort vs Quick Sort Bucket Sort and Quick Sort are two different sorting algorithms, each with its own characteristics, advantages, and disadvantages. In this article, we will provide a detailed overview of all the differences between Bucket Sort and Quick Sort. Bucket Sort:Bucket Sort is a non-comparison sorting algorithm that divides the input array into a number of 3 min read C Program for Iterative Quick Sort C/C++ Code // An iterative implementation of quick sort #include &lt;stdio.h&gt; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function is same in both iterative and recursive*/ int partition(int arr[], int l, int h) { int x = arr[h]; int i = (l - 1); for (int j = l; j &lt; 4 min read p5.js | Quick Sort QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick first element as pivot. Always pick last element as pivot. Pick a random element as pivot. Pick median as pivot. Approach: Fir 3 min read Advanced Quick Sort (Hybrid Algorithm) Prerequisites: Insertion Sort, Quick Sort, Selection SortIn this article, a Hybrid algorithm with the combination of quick sort and insertion sort is implemented. As the name suggests, the Hybrid algorithm combines more than one algorithm. Why Hybrid algorithm: Quicksort algorithm is efficient if the size of the input is very large. But, insertion 9 min read Visualization of Quick sort using Matplotlib Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, Approach : We will generate an array with random elements.The algorithm will be called on that arr 3 min read 3D Visualisation of Quick Sort using Matplotlib in Python Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use Matplotlib to plot bar graphs and animate them to represent the elements of the array. Let's see the 3D Visualizations of 3 min read Improvement on the Quick Sort Algorithm Prerequisite: QuickSort Algorithm The quicksort algorithm discussed in this article can take O(N2) time in the worst case. Hence, certain variations are needed which can efficiently partition the array and rearrange the elements around the pivot. Single Pivot Partitioning: In single pivot partitioning the array A[] can be divided into {A[p], A[p + 6 min read Quick Sort(Hoare's Partition) Visualization using JavaScript [video width="786" height="514" mp4="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210225121659/hoare.mp4"][/video]GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned into two parts and how we get the fina 4 min read

Article Tags :

  • C Misc Programs
  • Geeks Premier League 2023
  • Quick Sort
  • C Language

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Quick Sort in C - GeeksforGeeks (3)

Quick Sort in C - GeeksforGeeks (2024)

References

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 6205

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.