Quick Sort in Data Structure: Algorithm and Time Complexity

Data Structure / Sorting Laboratory Chapter 46
Quick Sort in Data Structure: Algorithm and Time Complexity

Understand Divide and Conquer, pivots, partitioning, recursive sorting, dry runs, C programming, complexity analysis and practical examples.

Pivot Selection Lomuto & Hoare Complete C Program Interactive Tracer Exam Ready
quicksort.trace
INPUT 29 10 14 37 13 PIVOT = 13 LEFT = 10 RIGHT = 14 37 29 SORTED 10 13 14 29 37

Imagine you have a list of numbers that must be arranged in ascending order. You could repeatedly compare neighbouring values, but there is another approach: choose one element and divide the remaining values around it.

This is the basic idea behind Quick Sort. Rather than arranging the complete array through repeated full passes, Quick Sort partitions the data into smaller problems and sorts those parts recursively.

Students often find Quick Sort confusing because of its pivot selection, partition index and recursive function calls. Understanding why the pivot reaches its correct position is more useful than simply memorising the program.

In this chapter, we will learn Quick Sort in Data Structure with a clear algorithm, original dry run, complete C program, working visualizer and detailed time and space complexity analysis.

Quick Answer / Definition

Quick Sort is a comparison-based sorting algorithm that follows the Divide and Conquer technique. It selects a pivot, partitions the array into smaller regions around that pivot, and recursively sorts the resulting subarrays. Its average time complexity is O(n log n), while the standard worst-case complexity is O(n²).

01 / Foundation

What Is Quick Sort in Data Structure?

Quick Sort in Data Structure: Algorithm and Time Complexity

Quick Sort is an efficient sorting method that divides a larger problem into smaller problems.

It selects an element called a pivot and rearranges the array around that element. This operation is known as partitioning.

In a typical ascending-order partition, elements not greater than the pivot are placed on one side, while greater elements are placed on the other.

The same process is then applied recursively to the smaller subarrays until they become sorted.

Simple Quick Sort Example

Original Array
29 10 14 37 13
↓ Partition
10 13 14 37 29

Pivot 13 reaches its final position. The right region still needs sorting.

Important Characteristics of Quick Sort

  • It is a Divide and Conquer algorithm.
  • It is comparison-based.
  • It works through partitioning.
  • It can sort an array without creating another full-sized array.
  • Standard implementations are not stable.
  • It usually uses recursion.
  • Its performance depends on how balanced the partitions are.

Remember: Quick Sort is not called Quick Sort because it is always the fastest algorithm. Its name reflects its generally efficient practical performance, but it can still be slow on certain inputs.

02 / Main working logic

How Does Quick Sort Work?

Quick Sort uses three major ideas: choosing a pivot, partitioning around it and recursively sorting the remaining regions.

STEP 01 Select Pivot

Choose an element from the active subarray.

STEP 02 Partition

Arrange values around the selected pivot.

STEP 03 Recurse

Sort the smaller left and right regions.

STEP 04 Finish

Stop when every region has at most one element.

What Is a Pivot in Quick Sort?

A pivot is the selected value used to divide the current subarray during partitioning.

In the standard Lomuto method used in this chapter, the last element is selected as the pivot.

After partitioning, the pivot is placed at its final sorted position. The elements on either side are then handled recursively.

Common Pivot Selection Methods

First or Last Element

Easy to understand and implement. However, fixed pivot selection can create poor partitions for certain input arrangements.

Random Pivot

Selects a random position, reducing predictable input patterns that consistently produce poor partitions.

Middle Element

Chooses the element at the middle index. It does not necessarily choose the median value.

Median-of-Three

Often selects the median of the first, middle and last values as a pivot heuristic.

Important: Selecting the middle-index element is different from finding the actual median of the values. Neither a middle-index pivot nor median-of-three guarantees balanced partitions on all inputs.

03 / Solved numerical

Quick Sort Example with Step-by-Step Dry Run

Let us sort the array 29, 10, 14, 37, 13 using Quick Sort in ascending order.

We will use Lomuto partitioning and choose the last element of each active subarray as the pivot.

Input: 29 10 14 37 13 Low = 0 High = 4 Pivot = A[4] = 13

Pass 1 — Partition Around Pivot 13

Start scanning from the first element. Values less than or equal to 13 belong in the left region.

Element Comparison Action
29 29 > 13 Leave in the greater-value region
10 10 <= 13 Move 10 into the left region
14 14 > 13 No swap
37 37 > 13 No swap

After scanning, place pivot 13 immediately after the smaller-value region.

First Partition Result
10 13 14 37 29

Pivot 13 is fixed at index 1. Left subarray: [10]. Right subarray: [14, 37, 29].

Pass 2 — Sort the Right Subarray

The left subarray contains only 10, so it is already sorted. The right subarray contains:

14 37 29 New Pivot = 29 14 <= 29 → Remains on left 37 > 29 → Remains on right Place 29 at its final index.
Second Partition Result
10 13 14 29 37

Pivot 29 is now fixed at index 3. The remaining subarrays contain single elements.

Pass 3 — Apply the Base Case

The remaining subarrays are [14] and [37]. Each contains one element, so no further partitioning is necessary.

Final Sorted Array: 10 13 14 29 37

Complete Quick Sort Dry Run Table

Stage Pivot Array State Comparisons
Initial – 29, 10, 14, 37, 13 0
Partition 1 13 10, 13, 14, 37, 29 4
Partition 2 29 10, 13, 14, 29, 37 2
Finish – 10, 13, 14, 29, 37 0
Total – Sorted 6
Dry Run Result

The sorted array is 10, 13, 14, 29, 37. With the implementation used here, the algorithm makes 6 pivot comparisons and 3 actual swaps. Swapping a position with itself is not counted as an actual swap.

Quick Sort Recursion Tree

Quick Sort does not repeatedly sort the full array. It recursively works only on the subarrays that still need sorting.

QuickSort(0, 4) | Pivot = 13 | Index 1 / \ [10] [14,37,29] | Pivot 29 | Index 3 / \ [14] [37] Result: 10 13 14 29 37

Very Important: A new pivot is selected inside each recursive subarray. Do not keep using the original pivot for every recursive call.

04 / Pseudocode

Quick Sort Algorithm in Data Structure

The following pseudocode uses Lomuto partitioning with the last element as the pivot.

Quick Sort Algorithm

QuickSort(A, low, high)
Algorithm QuickSort(A, low, high)

1. If low >= high
       Return

2. pivotIndex = Partition(A, low, high)

3. QuickSort(A, low, pivotIndex - 1)

4. QuickSort(A, pivotIndex + 1, high)

Lomuto Partition Algorithm

Partition(A, low, high)
Algorithm Partition(A, low, high)

1. pivot = A[high]

2. i = low

3. For j = low to high - 1

       If A[j] <= pivot

           Swap A[i] and A[j]

           i = i + 1

       End If

   End For

4. Swap A[i] and A[high]

5. Return i

Explanation of Important Variables

Variable Purpose
low Starting index of the active subarray
high Ending index of the active subarray
pivot Selected value used for partitioning
i Next position in the smaller-value region
j Current element being scanned
pivotIndex Final position of pivot after Lomuto partitioning

Base Case of Quick Sort

Recursion stops when the active subarray has zero or one element. Such a subarray is already sorted.

if (low >= high) return;

Without a correct base case and shrinking recursive ranges, the function may continue calling itself incorrectly.

05 / Partition methods

Lomuto Partition vs Hoare Partition in Quick Sort

Partitioning is the central operation of Quick Sort. Two important partition techniques are Lomuto and Hoare.

1. Lomuto Partition Scheme

Lomuto partitioning commonly chooses the last element as the pivot and uses a boundary index to group smaller values.

Each element is checked against the pivot. When it belongs on the smaller side, it is moved into that region.

Finally, the pivot is placed into its correct sorted position.

2. Hoare Partition Scheme

Hoare partitioning uses two pointers that scan from opposite directions. It exchanges elements that are on the wrong sides of the pivot value.

A common version chooses the first element as the pivot. The pointers move inward until they meet or cross.

The returned boundary divides the current subarray into two regions that must be sorted recursively.

Hoare Partition Pseudocode

HoarePartition(A, low, high)
pivot = A[low]
i = low - 1
j = high + 1

Repeat:

    Repeat:
        i = i + 1
    Until A[i] >= pivot

    Repeat:
        j = j - 1
    Until A[j] <= pivot

    If i >= j:
        Return j

    Swap A[i] and A[j]

Critical Difference: Hoare partition returns a partition boundary, not necessarily the final sorted index of the pivot. With this Hoare scheme, recursive ranges are low..p and p+1..high. Do not blindly use Lomuto's recursive boundaries.

Lomuto vs Hoare Comparison

Feature Lomuto Hoare
Scanning One main forward scan Two inward scans
Typical Pivot Last element First element
Returned Index Final pivot index Partition boundary
Implementation Generally simpler Needs careful pointer logic
Time per Partition O(n) O(n)
Stability Not stable Not stable

Exam Focus: For beginner practicals, Lomuto is often easier to trace. Hoare's method is worth studying because it usually makes fewer swaps and uses a different recursion boundary.

06 / Algorithm analysis

Quick Sort Time Complexity and Space Complexity

The time complexity of Quick Sort mainly depends on how the pivot divides the active array after each partition.

O(n log n) Best-case time
O(n log n) Average-case time
O(n²) Worst-case time

Best-Case Time Complexity: O(n log n)

The best case occurs when the pivot repeatedly divides the array into nearly equal-sized subarrays.

Each level of recursion processes a total of O(n) elements, and balanced divisions create approximately log n levels.

T(n) = 2T(n/2) + O(n) Balanced recursion levels ≈ log n Best Time = O(n log n)

Average-Case Time Complexity: O(n log n)

On average, the partitions are reasonably balanced across the recursive calls.

This gives Quick Sort an average time complexity of O(n log n).

Worst-Case Time Complexity: O(n²)

The worst case occurs when the pivot repeatedly produces very unbalanced partitions.

For example, choosing the last element as pivot in an already sorted array can leave one side empty and the other containing almost all remaining elements.

T(n) = T(n - 1) + O(n) Work approximately: (n - 1) + (n - 2) + ... + 1 = n(n - 1) / 2 Worst Time = O(n²)

Why Does Pivot Selection Matter?

Poor pivot choices create deep recursion and more work. Randomised pivot selection reduces the chance of consistently poor splits for fixed input patterns.

However, randomisation does not remove the theoretical O(n²) worst-case bound.

Quick Sort Space Complexity

Standard array-based Quick Sort normally rearranges elements within the original array. Its partitioning operation uses O(1) additional working space.

But recursive calls need stack memory, which depends on the recursion depth.

Case Time Recursion Stack
Best O(n log n) O(log n)
Average O(n log n) O(log n) expected
Worst O(n²) O(n)

Do Not Confuse: Quick Sort may use an in-place partitioning method, but recursive Quick Sort does not always have O(1) total auxiliary space. The recursion stack must also be considered.

Is Quick Sort Stable?

Standard Quick Sort is not stable. Partition swaps can change the original relative order of records with equal keys.

Special stable variations exist, but they require different design choices and may use additional memory.

07 / Interactive learning

Interactive Quick Sort Visualizer

Quick Sort becomes easier when you can see the pivot and partition movements.

This visualizer uses Lomuto partitioning. It shows comparisons, swaps, pivot placement and recursive subarray sorting.

Quick Sort Partition Lab

Enter your own numbers, choose ascending or descending, and follow the sorting process.

Enter 3 to 8 whole numbers from -99 to 999, separated by commas.

Active Value Pivot Comparing Fixed Position
0 Comparisons
0 Actual Swaps
0 Recursion Depth

Ready to begin Quick Sort.

Practice: Try 29, 10, 14, 37, 13. Next, enter 1, 2, 3, 4, 5. Notice how last-element pivot selection can create unbalanced partitions for already sorted input.

08 / Programming practical

Quick Sort Program in C with Output

The following complete C program uses Lomuto partitioning. It supports ascending and descending sorting.

The program also displays the array after each pivot is placed and calculates the number of comparisons and actual swaps.

Complete Quick Sort C Program

quick_sort.c — C11 Program
#include <stdio.h>

#define MAX 100

void exchange(
    int a[],
    int x,
    int y,
    long long *swaps
) {
    if (x == y) {
        return;
    }

    int temp = a[x];
    a[x] = a[y];
    a[y] = temp;

    ++(*swaps);
}

void show(const int a[], int n) {
    for (int i = 0; i < n; ++i) {
        printf(
            "%d%s",
            a[i],
            (i == n - 1) ? "" : " "
        );
    }

    putchar('\n');
}

int partition(
    int a[],
    int low,
    int high,
    int order,
    long long *comparisons,
    long long *swaps
) {
    int pivot = a[high];
    int border = low;

    for (int j = low; j < high; ++j) {

        ++(*comparisons);

        if (
            (order == 1 && a[j] <= pivot) ||
            (order == 2 && a[j] >= pivot)
        ) {
            exchange(a, border, j, swaps);
            ++border;
        }
    }

    exchange(a, border, high, swaps);

    return border;
}

void quickSort(
    int a[],
    int low,
    int high,
    int n,
    int order,
    long long *comparisons,
    long long *swaps
) {
    if (low >= high) {
        return;
    }

    int pivotValue = a[high];

    int p = partition(
        a, low, high, order,
        comparisons, swaps
    );

    printf(
        "Pivot %d at index %d: ",
        pivotValue, p
    );

    show(a, n);

    quickSort(
        a, low, p - 1, n,
        order, comparisons, swaps
    );

    quickSort(
        a, p + 1, high, n,
        order, comparisons, swaps
    );
}

int main(void) {

    int a[MAX], n, order;

    long long comparisons = 0;
    long long swaps = 0;

    printf(
        "Enter number of elements (1-100): "
    );

    if (
        scanf("%d", &n) != 1 ||
        n < 1 || n > MAX
    ) {
        puts("Invalid array size.");
        return 1;
    }

    printf("Enter %d integers: ", n);

    for (int i = 0; i < n; ++i) {

        if (scanf("%d", &a[i]) != 1) {
            puts("Invalid integer input.");
            return 1;
        }
    }

    printf(
        "Enter 1 for ascending "
        "or 2 for descending: "
    );

    if (
        scanf("%d", &order) != 1 ||
        (order != 1 && order != 2)
    ) {
        puts("Invalid order choice.");
        return 1;
    }

    quickSort(
        a, 0, n - 1, n, order,
        &comparisons, &swaps
    );

    printf("Sorted array: ");
    show(a, n);

    printf(
        "Pivot comparisons: %lld\n"
        "Actual swaps: %lld\n",
        comparisons, swaps
    );

    return 0;
}

Sample Input

Program Input
Enter number of elements (1-100): 5
Enter 5 integers: 29 10 14 37 13
Enter 1 for ascending or 2 for descending: 1

Output of Quick Sort C Program

Expected Output
Pivot 13 at index 1: 10 13 14 37 29
Pivot 29 at index 3: 10 13 14 29 37
Sorted array: 10 13 14 29 37
Pivot comparisons: 6
Actual swaps: 3

Explanation of the C Program

1. exchange() Function

Exchanges two array elements when their indices are different. It also updates the actual swap counter.

2. partition() Function

Selects the last element as pivot, scans the active subarray and returns the pivot's final index.

3. quickSort() Function

First checks the base case. It then partitions the array and recursively sorts both remaining subarrays.

4. Comparison Counter

Counts each array-element comparison against a pivot. It does not count loop conditions or boundary checks.

5. Actual Swap Counter

Increases only when two different array positions exchange values. Self-swaps are skipped.

6. main() Function

Reads the input array and sorting order, calls Quick Sort, and displays the final result.

Program Testing: This C11 program was compiled successfully using GCC with warnings enabled. Ascending, descending, sorted, reverse-sorted, duplicate and negative-value inputs were tested.

How to Run Quick Sort in VS Code

  1. Open VS Code with GCC installed.
  2. Create quick_sort.c.
  3. Paste the complete C program.
  4. Open the terminal.
  5. Compile and run the program.
GCC Compilation Command
gcc -std=c11 -Wall -Wextra quick_sort.c -o quick_sort

Windows PowerShell:

Run Executable
.\quick_sort.exe
09 / Comparisons and choices

Quick Sort vs Merge Sort vs Heap Sort

These three algorithms have O(n log n) average time complexity, but differ in their worst-case performance, memory requirements and stability.

Feature Quick Sort Merge Sort Heap Sort
Approach Partition by pivot Divide and merge Build and process heap
Best Time O(n log n) O(n log n) O(n log n)
Average Time O(n log n) O(n log n) O(n log n)
Worst Time O(n²) O(n log n) O(n log n)
Typical Auxiliary Space O(log n) expected stack O(n), array version O(1), iterative heapify
Stable No, normally Yes, standard version No, normally

Quick Sort vs Merge Sort

Quick Sort rearranges elements around pivots and then recursively sorts the resulting regions. Merge Sort recursively divides data and merges sorted portions.

Standard Merge Sort provides predictable O(n log n) worst-case time, but its typical array implementation requires O(n) auxiliary memory.

Quick Sort vs Heap Sort

Heap Sort uses a binary heap and guarantees O(n log n) worst-case time.

Quick Sort can be very efficient for ordinary array sorting, but standard implementations may degrade to O(n²).

Advantages of Quick Sort

  • Efficient average-case running time.
  • Works directly within the array in common implementations.
  • Good memory locality in many practical scenarios.
  • Useful for understanding recursion and Divide and Conquer.
  • Can be improved using pivot-selection heuristics.

Disadvantages of Quick Sort

  • O(n²) worst-case running time.
  • Not stable in standard implementations.
  • Recursive calls consume stack space.
  • Poor pivot choices can create deep recursion.
  • Simple two-way partitioning may perform poorly on many duplicate values.

How Are Duplicate Values Handled?

In Lomuto partitioning, using the condition A[j] <= pivot places equal values in the left region.

When many values are equal, this can create unbalanced recursive partitions.

Three-way Quick Sort is a useful alternative because it divides values into three groups: less than, equal to, and greater than the pivot.

10 / Debugging guide

Common Mistakes in Quick Sort

Mistake Correct Explanation
Using the original pivot for every recursive call Select a pivot for each active subarray.
Forgetting the base case Stop when low is greater than or equal to high.
Using incorrect partition bounds Check whether your code uses Lomuto or Hoare.
Always writing O(n log n) Standard worst-case time is O(n²).
Claiming O(1) total extra space Include recursion stack memory.
Assuming Quick Sort is stable Standard partition swaps can change equal-key order.
Confusing index and pivot value The pivot value and its final position are different concepts.

Most Important Recursion Mistake

A common Lomuto error is to call Quick Sort on a range that includes the already fixed pivot again.

Correct Lomuto Recursion
quickSort(a, low, p - 1, ...);
quickSort(a, p + 1, high, ...);

In Lomuto partitioning, the pivot is already correctly placed at p, so it must be excluded from both recursive calls.

11 / University exams

Important Quick Sort Questions and Answers

These are original exam-style revision questions. The mark values suggest answer lengths; they are not claimed to be verified university PYQs.

2 MARKS

1. Define Quick Sort.

Quick Sort is a Divide and Conquer sorting algorithm that selects a pivot, partitions an array around it and recursively sorts the resulting subarrays.

2 MARKS

2. What Is a Pivot in Quick Sort?

A pivot is the selected element used to partition the active subarray during Quick Sort.

2 MARKS

3. What Is the Worst-Case Time Complexity?

The worst-case time complexity of standard Quick Sort is O(n²). It occurs when partitioning repeatedly produces highly unbalanced subarrays.

5 MARKS

4. Explain Quick Sort with an Example.

Quick Sort selects a pivot and rearranges values around it.

For the array 29, 10, 14, 37, 13, choose pivot 13. After the first Lomuto partition, the array becomes 10, 13, 14, 37, 29.

Sorting the right subarray around pivot 29 produces 10, 13, 14, 29, 37.

Average time complexity is O(n log n), while worst-case time complexity is O(n²).

5 MARKS

5. Differentiate Lomuto and Hoare Partitioning.

Lomuto partitioning usually performs a forward scan with a boundary index. The returned index represents the pivot's final position.

Hoare partitioning scans from both directions and returns a boundary separating the resulting regions.

Their recursion boundaries must match the partition method used.

10 MARKS

6. Explain Quick Sort Algorithm and Complexity.

Quick Sort is a comparison-based Divide and Conquer sorting algorithm.

It selects a pivot and partitions the active subarray so that elements appear on the appropriate sides of the pivot.

The partition process is followed by recursive calls on smaller subarrays. Recursion ends when a subarray contains at most one element.

With balanced partitions, the recurrence is T(n) = 2T(n/2) + O(n), which gives O(n log n) time.

With highly unbalanced partitions, the recurrence becomes T(n) = T(n-1) + O(n), giving O(n²) worst-case time.

The usual recursive implementation requires O(log n) expected stack memory and can require O(n) stack memory in the worst case.

Standard Quick Sort is not stable, but its efficient average performance makes it an important algorithm in Data Structure.

12 / Self-assessment

Quick Sort Practice Questions with Solutions

Question 1: What Is the Average Time Complexity?

A. O(n)
B. O(n log n)
C. O(n²)
D. O(1)

Show Answer

B. O(n log n). Quick Sort has average O(n log n) time complexity.

Question 2: Which Technique Does Quick Sort Use?

A. Greedy Method
B. Dynamic Programming
C. Divide and Conquer
D. Breadth-First Search

Show Answer

C. Divide and Conquer. It partitions a large problem into smaller sorting problems.

Question 3: Sort 8, 3, 7, 4, 2 Using Last-Element Pivot.

Show Solution

Start with pivot 2. It is the smallest value, so the first partition places it at index 0:

Initial: 8 3 7 4 2 After pivot 2: 2 3 7 4 8 Sort remaining: 3 7 4 8 Using pivot 8, then pivot 4: Final: 2 3 4 7 8

Each subsequent partition processes only the remaining unsorted subarray.

Question 4: Is Quick Sort Stable?

Show Answer

Standard Quick Sort is unstable because swapping elements during partitioning may change the relative order of equal-key records.

Question 5: Why Is Pivot Selection Important?

Show Explanation

Pivot selection affects the sizes of the resulting subarrays. Balanced partitions generally reduce recursion depth and work. Repeatedly unbalanced partitions may cause O(n²) running time.

13 / FAQs

Frequently Asked Questions About Quick Sort

What is Quick Sort in simple words?

Quick Sort chooses a pivot, divides values around it, and sorts the smaller groups recursively.

What is the time complexity of Quick Sort?

The best and average time complexity is O(n log n). The standard worst-case time complexity is O(n²).

What is the space complexity of Quick Sort?

A typical recursive implementation uses O(log n) stack space with balanced partitions and O(n) stack space in the worst case.

Which pivot is best for Quick Sort?

A pivot that divides the array into nearly equal-sized subarrays produces good performance. Random and median-of-three strategies are common heuristics.

Is Quick Sort an in-place algorithm?

Common array implementations perform partitioning in place. However, recursive calls still require stack memory.

What is Lomuto partition in Quick Sort?

Lomuto partition is a technique that uses a boundary index to group values around a pivot, commonly chosen as the last array element.

What is the difference between Quick Sort and Merge Sort?

Quick Sort partitions around pivots, while Merge Sort combines sorted subarrays. Standard Merge Sort guarantees O(n log n) worst-case time, while standard Quick Sort may take O(n²).

Why can Quick Sort be slow for sorted data?

With a poor fixed-pivot strategy, an already sorted array can produce extremely unbalanced recursive partitions, leading to O(n²) time.

14 / Quick revision

Quick Sort One-Minute Revision Notes

QUICK SORT Technique: Divide and Conquer Main Operation: Partitioning Pivot: Selected element Best Time: O(n log n) Average Time: O(n log n) Worst Time: O(n²) Typical Stack: O(log n) expected Worst Stack: O(n) Stability: Unstable, standard version

Memory Trick: Select Pivot → Partition → Sort Left → Sort Right → Stop.

Conclusion

Quick Sort in Data Structure is easier to understand when you focus on the pivot and partitioning process before writing the complete C program.

The algorithm selects a pivot, rearranges the active subarray and recursively sorts the smaller regions.

Quick Sort has O(n log n) average time complexity, but poor pivot selection can produce O(n²) worst-case performance.

For exams and practicals, practise the partition dry run, understand the base case, write the program yourself and remember the differences between Lomuto and Hoare.

Chapter 46 — Completed

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources