Quick Sort in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Quick Sort in C: Program to Sort Array Using Quick Sort Algorithm

πŸ“‘ On this page:
  • Introduction
  • C Program for Quick Sort
  • Sample Output
  • Program Explanation
  • Algorithm
  • Complexity Analysis
  • Practice Exercise
  • Frequently Asked Questions
πŸ“š In this tutorial, you will learn:
  • What is quick sort and how it works
  • How to implement quick sort in C using recursion
  • How quick sort uses the divide-and-conquer strategy with a pivot element
  • Step-by-step explanation of the program
  • Time and space complexity of quick sort
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to sort an array using the quick sort algorithm.

Quick sort is a highly efficient, comparison-based sorting algorithm that follows the divide-and-conquer paradigm. It works by selecting a pivot element from the array and partitioning the other elements into two sub-arraysβ€”those less than the pivot and those greater than the pivot. The sub-arrays are then recursively sorted.

πŸ’‘ Key Point: Quick sort is one of the fastest sorting algorithms in practice, with an average time complexity of O(n log n). It is widely used in real-world applications and is the default sorting algorithm in many programming languages.

Quick sort is used in various real-world applications, such as:

  • General-purpose Sorting: Default sorting algorithm in C's qsort() and C++'s std::sort
  • Large Datasets: Efficiently sorts large arrays with good average-case performance
  • In-place Sorting: Requires minimal extra memory
  • Embedded Systems: Used when memory is limited

Visual Example

Let's see how quick sort sorts the array [10, 7, 8, 9, 1, 5]:

Step 1: Choose pivot (last element: 5)

[10, 7, 8, 9, 1, 5] β†’ Partition around pivot 5
[1, 5, 8, 9, 10, 7] β†’ 5 is in correct position

Step 2: Recursively sort left subarray [1] and right subarray [8, 9, 10, 7]

[1] is already sorted
[8, 9, 10, 7] β†’ Choose pivot 7 β†’ Partition β†’ [7, 9, 10, 8]

Step 3: Recursively sort right subarray [9, 10, 8]

[9, 10, 8] β†’ Choose pivot 8 β†’ Partition β†’ [8, 10, 9]
[10, 9] β†’ Choose pivot 9 β†’ Partition β†’ [9, 10]

Final Sorted Array: [1, 5, 7, 8, 9, 10]

C Program for Quick Sort

#include <stdio.h>

// Function to swap two elements
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Partition function - places pivot in correct position
int partition(int arr[], int low, int high) {
    // Choose the rightmost element as pivot
    int pivot = arr[high];
    int i = (low - 1);  // Index of smaller element
    
    for(int j = low; j <= high - 1; j++) {
        // If current element is smaller than or equal to pivot
        if(arr[j] <= pivot) {
            i++;  // Increment index of smaller element
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

// Quick Sort function
void quickSort(int arr[], int low, int high) {
    if(low < high) {
        // pi is partitioning index, arr[pi] is now at correct position
        int pi = partition(arr, low, high);
        
        // Recursively sort elements before and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int n, i;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array
    int arr[n];
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Perform quick sort
    quickSort(arr, 0, n - 1);
    
    // Display sorted array
    printf("\nSorted array in ascending order: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Sample Output

Enter the number of elements: 6
Enter 6 elements:
10 7 8 9 1 5

Sorted array in ascending order: 1 5 7 8 9 10

Another Example:

Enter the number of elements: 8
Enter 8 elements:
64 34 25 12 22 11 90 5

Sorted array in ascending order: 5 11 12 22 25 34 64 90

Example with Negative Numbers:

Enter the number of elements: 6
Enter 6 elements:
-5 10 -2 8 0 -10

Sorted array in ascending order: -10 -5 -2 0 8 10

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. swap() Function:
    • Swaps two integer values using pointers
    • Used during the partitioning process
  3. partition() Function:
    • Selects the last element as the pivot
    • Places all elements smaller than the pivot to the left
    • Places all elements greater than the pivot to the right
    • Returns the final position of the pivot
  4. quickSort() Function:
    • Recursively sorts the array
    • Partitions the array and recursively sorts the left and right subarrays
  5. main() Function:
    • Gets user input for the array
    • Calls quickSort(arr, 0, n-1) to sort the array
    • Prints the sorted array

πŸ“ Note: Quick sort has an average time complexity of O(n log n) and is considered one of the fastest sorting algorithms in practice.

Quick Sort Algorithm

Step-by-step algorithm:

  1. Start
  2. Read the array elements
  3. If low < high:
    • Choose a pivot element (typically the last element)
    • Partition the array around the pivot
    • Recursively sort the left subarray: quickSort(arr, low, pi - 1)
    • Recursively sort the right subarray: quickSort(arr, pi + 1, high)
  4. Print the sorted array
  5. End

Time and Space Complexity

Scenario Time Complexity Space Complexity
Best Case (Balanced Partition) O(n log n) O(log n)
Worst Case (Already Sorted or Reverse Sorted) O(nΒ²) O(n)
Average Case O(n log n) O(log n)

πŸ’‘ Note: Quick sort is an in-place sorting algorithm, requiring only O(log n) extra space for the recursion stack in the average case.

πŸ’» Practice Exercise

Challenge 1: Modify the quick sort program to sort the array in descending order.

Challenge 2: Implement quick sort using a different pivot selection strategy (e.g., middle element, first element, or random pivot).

πŸ” Click to Show Solution for Challenge 1
// Change the comparison in the partition function
if(arr[j] >= pivot) {  // Change <= to >= for descending
    i++;
    swap(&arr[i], &arr[j]);
}

Frequently Asked Questions

1. What is quick sort in C?

Quick sort is a divide-and-conquer sorting algorithm that selects a pivot element, partitions the array around it, and recursively sorts the subarrays.

2. What is the time complexity of quick sort?

Quick sort has a time complexity of O(n log n) in the average and best cases, and O(nΒ²) in the worst case (when the pivot is the smallest or largest element).

3. Is quick sort stable?

No, quick sort is not stable because it swaps elements that are not necessarily adjacent, which can change the relative order of equal elements.

4. How can the worst-case performance of quick sort be improved?

The worst-case performance can be improved by using a randomized pivot selection or by using the median-of-three pivot selection strategy.

5. When should I use quick sort?

Quick sort is ideal for large datasets where average-case performance is important. It's the default sorting algorithm in many standard libraries due to its efficiency and in-place nature.

πŸ’‘ Tip: Quick sort is one of the most important sorting algorithms to learn. Its divide-and-conquer approach is used in many other algorithms like Binary Search and Merge Sort.

πŸ“– Related Tutorials

  • Bubble Sort in C
  • Selection Sort in C
  • Insertion Sort in C
  • Merge Sort in C
  • Heap Sort in C
  • More Array Assignments

Previous Topic: -->> Merge Sort in C   ||   Next topic: -->> Heap Sort in C


πŸ“š Explore More Topics

πŸ—„οΈ SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

🐍 Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

β˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.