Quick Sort Program in C

Problem Description

Write a C program to implement the Quick Sort algorithm.

Problem Solution

To approach this problem, we will use the divide and conquer algorithm.

What is Quick Sort?

Quick sort is a divide and conquer algorithm. It works by recursively partitioning the array into two parts, the left side of the array containing elements less than the pivot element, and the right side of the array containing elements greater than the pivot element.

Quick Sort Algorithm:

1. Pick an element, called a pivot, from the array.
2. Partition the array into two halves, the left side of the array containing elements less than the pivot element, and the right side of the array containing elements greater than the pivot element.
3. Recursively sort the left side of the array and the right side of the array.
4. Return the array.

There are several ways to write an Quick Sort program in C language. Let’s discuss all the ways in detail.

Method 1: QuickSort in C using Naive Approach

In this approach we will not use recursion. We will instead use a while loop to iterate through the array. We will pick a pivot element, and partition the array into two halves. We will then iterate through the array again, and pick a new pivot element, and partition the array into two halves. We will continue this process until we have only one element left in the array.

advertisement
advertisement

Methods used:
int quickSort(int arr[], int low, int high): This function will take in an array, and the low and high indices of the array.

Program/Source Code

Here is source code of the C Program to sort an array of integers using QuickSort Algorithm. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

  1. /*
  2.  * C Program to sort an array of integers using Quick Sort without recursion
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. int quickSort(int *arr, int low, int high)
  9. {
  10.     int i = low, j = high;
  11.     int pivot = arr[(low + high) / 2];
  12.     while (i <= j)
  13.     {
  14.         while (arr[i] < pivot)
  15.             i++;
  16.         while (arr[j] > pivot)
  17.             j--;
  18.         if (i <= j)
  19.         {
  20.             int temp = arr[i];
  21.             arr[i] = arr[j];
  22.             arr[j] = temp;
  23.             i++;
  24.             j--;
  25.         }
  26.     }
  27.     if (low < j)
  28.         quickSort(arr, low, j);
  29.     if (i < high)
  30.         quickSort(arr, i, high);
  31.     return 0;
  32. }
  33.  
  34. int main(void)
  35. {
  36.     puts("Enter the number of elements in the array: ");
  37.     int n;
  38.     scanf("%d", &n);
  39.     int arr[n];
  40.     puts("Enter the elements of the array: ");
  41.     for (int i = 0; i < n; i++)
  42.     {
  43.         printf("arr[%d]: ", i);
  44.         scanf("%d", &arr[i]);
  45.     }
  46.     int low = 0;
  47.     int high = n - 1;
  48.     int pivot = arr[high];
  49.     int k = low - 1;
  50.     for (int j = low; j < high; j++)
  51.     {
  52.         if (arr[j] <= pivot)
  53.         {
  54.             k++;
  55.             int temp = arr[k];
  56.             arr[k] = arr[j];
  57.             arr[j] = temp;
  58.         }
  59.     }
  60.     int temp = arr[k + 1];
  61.     arr[k + 1] = arr[high];
  62.     arr[high] = temp;
  63.     int pi = k + 1;
  64.     quickSort(arr, low, pi - 1);
  65.     quickSort(arr, pi + 1, high);
  66.     puts("The sorted array is: ");
  67.     for (int i = 0; i < n; i++)
  68.     {
  69.         printf("%d ", arr[i]);
  70.     }
  71.     return 0;
  72. }
Program Explanation

1. The program starts with asking the user for entering the size for the array and subsequently entering the array elements.
2. Then we will pick a pivot element, and partition the array into two halves.
3. We will then iterate through the array again, and pick a new pivot element, and partition the array into two halves.
4. We will continue this process until we have only one element left in the array.
5. The final array will then be returned and printed.

Note: Join free Sanfoundry classes at Telegram or Youtube

Example:

  • Suppose we have the following array: {4, 7, 2, 9, 11, 3, 1, 6}
  • Assign low as 0 and high as n – 1. We set the pivot element to the element with the index high.
  • Here, high is 7 and pivot is 6. We set k as low – 1 which is -1 here. While entering the loop, k becomes 1 and for all elements with indices equal to low and less than high are compared and if they are less than or equal to the pivot element, we swap them.
  • We set temp as the element at index k + 1 and swap it with the element at index high. We then set pi as k + 1.
  • We continue this process until we have only one element left in the array. We finally sent the array, lower index and upper index to the quickSort function.
  • In the quickSort function, we assign i as low and j as high. We set the element at the middle index as the pivot.
  • Increment the i by the number of elements which are less than the pivot element. We then decrement j by the number of elements which are greater than the pivot element.
  • Swap the element at index i with the element at index j. If i is less than equal to j which means we are checking here for the condition when all the elements have been sorted then it should not work.
  • Next, set the pivot element as the element at index j. We then continue this process until we have only one element left in the array and this loop continues until i is not greater than j.
  • Call the same function recursively on the left side of the array and the right side of the array.
  • Finally, print the array.

Time Complexity: O(N log N)
The time complexity of the quick sort algorithm is O(N log N).

Space Complexity: O(n)
The space complexity for quick sort is O(n).

Runtime Test Cases

Here’s the run time test cases for Quick Sort algorithm for 2 different input cases.

Test Case 1: Here, the elements are entered in random order.

advertisement
Enter the number of elements in the array: 
8
Enter the elements of the array: 
arr[0]: 4
arr[1]: 7
arr[2]: 2
arr[3]: 9
arr[4]: 11
arr[5]: 3
arr[6]: 1
arr[7]: 6
The sorted array is: 
1 2 3 4 6 7 9 11

Test Case 2: Here, the elements are reverse sorted.

Enter the number of elements in the array: 
5
Enter the elements of the array: 
arr[0]: 7
arr[1]: 3
arr[2]: 2
arr[3]: 1
arr[4]: -6
The sorted array is: 
-6 1 2 3 7

Method 2: (Recursion)

In this approach we will use recursion. We will pick a pivot element, and partition the array into two halves. We will then recursively sort the left side of the array and the right side of the array. We will then return the array.

advertisement

Methods used:
The methods used are:

  • void quickSort(int arr[], int low, int high)
  • int partition(int arr[], int low, int high)
Program/Source Code

Here is source code of the C program to perform quick sort on a user provided array using recursion. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

  1. /*
  2.  * C program to perform quick sort on a user provided array using recursion
  3.  */
  4.  
  5. #include <stdio.h>
  6.  
  7. int partition(int ar[], int low, int high)
  8. {
  9.     int pivot = ar[high];
  10.     int i = low - 1;
  11.     for (int j = low; j < high; j++)
  12.     {
  13.         if (ar[j] <= pivot)
  14.         {
  15.             i++;
  16.             int temp = ar[i];
  17.             ar[i] = ar[j];
  18.             ar[j] = temp;
  19.         }
  20.     }
  21.     int temp = ar[i + 1];
  22.     ar[i + 1] = ar[high];
  23.     ar[high] = temp;
  24.     return i + 1;
  25. }
  26.  
  27. void quickSort(int arr[], int low, int high)
  28. {
  29.     if (low < high)
  30.     {
  31.         int pi = partition(arr, low, high);
  32.  
  33.         quickSort(arr, low, pi - 1);
  34.         quickSort(arr, pi + 1, high);
  35.     }
  36. }
  37.  
  38. int main(void)
  39. {
  40.     puts("Enter the number of elements in the array: ");
  41.     int n;
  42.     scanf("%d", &n);
  43.     int arr[n];
  44.     puts("Enter the elements of the array: ");
  45.     for (int i = 0; i < n; i++)
  46.     {
  47.         printf("%d: ", i);
  48.         scanf("%d", &arr[i]);
  49.     }
  50.     quickSort(arr, 0, n - 1);
  51.     puts("The sorted array is: ");
  52.     for (int i = 0; i < n; i++)
  53.     {
  54.         printf("%d ", arr[i]);
  55.     }
  56. }
Program Explanation

1. The program starts with asking the user to enter the size of the array.
2. Then we will enter the elements of the array.
3. Call the quickSort function on the array.
4. Check if low is less than high, if it is then we will pick a pivot element, and partition the array into two halves.
5. We will then recursively sort the left side of the array and the right side of the array.
6. Print the array.

Example:

  • For example, suppose we have the following array: {12, 76, 33, 65, 5, 88} Control goes into quickSort(arr, 0, 5).
  • Low is less than high, thus partition(arr, 0, 5) is invoked. pivot is the last element ie. 4. We set i as low – 1 which is -1 here.
  • While entering the loop, k becomes 1 and for all elements with indices equal to low and less than high are compared and if they are less than or equal to the pivot element, we swap them.
  • We set temp as the element at index i + 1 and swap it with the element at index high. We then return and set pi as i + 1.
  • We continue this process until we have only one element left in the array. We then print the result.

Time Complexity: O(N log N)
The time complexity of the quick sort algorithm is O(N log N).

Space Complexity: O(n)
The space complexity for quick sort is O(n).

Runtime Test Cases

In this case, the elements are entered in a random order. The elements entered to sort the array using quick sort are “12, 76, 33, 65, 5, 88”.

Enter the number of elements in the array: 
6
Enter the elements of the array: 
arr[0]: 12
arr[1]: 76
arr[2]: 33
arr[3]: 65
arr[4]: 5
arr[5]: 88
The sorted array is: 
5 12 33 65 76 88

Method 3: (Recursion and Modular Approach)

In this approach, in addition to having recursion in order to keep our code as small as possible, we’ll also be taking care not to reuse things and taking care for memory safety whenever possible. For this, we make sure that we don’t use the same array twice, and that we don’t use the same pointer twice. We’ll also use malloc to allocate memory for the array and swap function to swap two elements.

Methods used:
The methods used are:

  • `malloc` to allocate memory for the array — inbuilt function.
  • `swap` to swap two elements. — without using auxillary variable.
  • `partition` to partition the array.
  • `quickSort` to sort the array.
Program/Source Code

Here is source code of the C program to perform quick sort on a user provided array using recursion and malloc. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

  1. /*
  2.  * C program to perform quick sort on a user provided array using recursion and malloc
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. int n;
  9.  
  10. void printarray(int ar[], const char *name, unsigned int size)
  11. {
  12.     printf("%s[] = [", name);
  13.     for (unsigned int i = 0; i < size; i++)
  14.         printf(" %d", ar[i]);
  15.     puts(" ]\n");
  16. }
  17.  
  18. void swap(int *a, int *b)
  19. {
  20.     if(*a == *b) return;
  21.     *a = *a + *b;
  22.     *b = *a - *b;
  23.     *a = *a - *b;
  24. }
  25.  
  26. int partition(int *ar, int low, int high)
  27. {
  28.     int pivot = ar[high];
  29.     int i = low - 1;
  30.     for (int j = low; j < high; j++)
  31.     {
  32.         if (ar[j] <= pivot)
  33.         {
  34.             i++;
  35.             swap(&ar[i], &ar[j]);
  36.         }
  37.     }
  38.     swap(&ar[i + 1], &ar[high]);
  39.     return i + 1;
  40. }
  41.  
  42. void quickSort(int *arr, int low, int high)
  43. {
  44.     if (low < high)
  45.     {
  46.         int pi = partition(arr, low, high);
  47.         quickSort(arr, low, pi - 1);
  48.         printarray(arr, "arr", (unsigned) n);
  49.         quickSort(arr, pi + 1, high);
  50.         printarray(arr, "arr", (unsigned) n);
  51.     }
  52. }
  53.  
  54. int main(void)
  55. {
  56.     puts("Enter the number of elements in the array: ");
  57.  
  58.     scanf("%d", &n);
  59.     int *arr = malloc((size_t) n * sizeof(n));
  60.     puts("Enter the elements of the array: ");
  61.     for (int i = 0; i < n; i++)
  62.     {
  63.         printf("%d: ", i);
  64.         scanf("%d", &arr[i]);
  65.     }
  66.     quickSort(arr, 0, n - 1);
  67. }
Program Explanation

1. The program starts with asking the user to enter the size of the array and then assigns it space with malloc.
2. Then the user enters the elements of the array.
3. Call the quickSort function on the array. We check if low is less than high, if it is then we will pick a pivot element, and partition the array into two halves.
4. We will then recursively sort the left side of the array and the right side of the array.
5. Print the array.

Example:

  • Suppose we have the following array: {4, 6, 3, 5, 1, 2, 7, 8} defined through malloc.
  • Call the quickSort function on the array. Control goes into quickSort(arr, 0, 7). Low is less than high, thus partition(arr, 0, 7) is invoked. pivot is the last element ie. 8.
  • We set i as low – 1 which is -1 here. While entering the loop, k becomes 1 and for all elements with indices equal to low and less than high are compared and if they are less than or equal to the pivot element, we swap them using the swap function.
  • We set temp as the element at index i + 1 and swap it with the element at index high. We then return and set pi as i + 1.
  • We continue this process until we have only one element left in the array. We then print the result.

Time Complexity: O(N log N)
The time complexity of the quick sort algorithm is O(N log N).

Space Complexity: O(n)
The space complexity for quick sort is O(n).

Runtime Test Cases

In this case, the elements are entered in a random order. The elements entered to sort the array using quick sort are “4, 6, 3, 5, 1, 2, 7, 8”.

Enter the number of elements in the array: 
8
Enter the elements of the array: 
arr[0]: 4
arr[1]: 6
arr[2]: 3
arr[3]: 5
arr[4]: 1
arr[5]: 2
arr[6]: 7
arr[7]: 8
The sorted array is: 
1 2 3 4 5 6 7 8

Method 4: Quick Sort in C using Randomization

In this approach, it sorts a given array of integer numbers using randomized Quick sort technique.

Program/Source Code

Here is source code of the C program to perform quick sort using randomization. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on Windows 10. The program output is also shown below.

  1. /*
  2.  * C Program to Implement Quick Sort Using Randomization
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #define MAX 100
  8. void random_shuffle(int arr[])
  9. {
  10.     srand(time(NULL));
  11.     int i, j, temp;
  12.     for (i = MAX - 1; i > 0; i--)
  13.     {
  14.         j = rand()%(i + 1);
  15.         temp = arr[i];
  16.         arr[i] = arr[j];
  17.         arr[j] = temp;
  18.     }
  19. }
  20.  
  21. void swap(int *a, int *b)
  22. {
  23.     int temp;
  24.     temp = *a;
  25.     *a = *b;
  26.     *b = temp;
  27. }
  28. int partion(int arr[], int p, int r)
  29. {
  30.     int pivotIndex = p + rand()%(r - p + 1); //generates a random number as a pivot
  31.     int pivot;
  32.     int i = p - 1;
  33.     int j;
  34.     pivot = arr[pivotIndex];
  35.     swap(&arr[pivotIndex], &arr[r]);
  36.     for (j = p; j < r; j++)
  37.     {
  38.         if (arr[j] < pivot)
  39.         {
  40.             i++;
  41.             swap(&arr[i], &arr[j]);
  42.         }
  43.  
  44.     }
  45.     swap(&arr[i+1], &arr[r]);
  46.     return i + 1;
  47. }
  48.  
  49. void quick_sort(int arr[], int p, int q)
  50. {
  51.     int j;
  52.     if (p < q)
  53.     {
  54.         j = partion(arr, p, q);
  55.         quick_sort(arr, p, j-1);
  56.         quick_sort(arr, j+1, q);
  57.     }
  58. }
  59. int main()
  60. {
  61.     int i;
  62.     int arr[MAX];
  63.     for (i = 0; i < MAX; i++)
  64.         arr[i] = i;
  65.     random_shuffle(arr); //To randomize the array
  66.     quick_sort(arr, 0, MAX-1); //function to sort the elements of array
  67.     for (i = 0; i < MAX; i++)
  68.          printf("%d \n", arr[i]);
  69.     return 0;
  70. }
Program Explanation

1. This code implements the Quick Sort algorithm to sort an array of integers.
2. The code first randomly shuffles the array using the random_shuffle function.
3. Then, it calls the quick_sort function to recursively sort the array.
4. The quick_sort function partitions the array around a pivot element and then recursively sorts the two subarrays.
5. Finally, the code prints the sorted array.

Runtime Test Cases
Sorted array is : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.