Skip to content
Home Ā» Quick sort

Quick sort


šŸ“˜ Quick Sort (with Running Time Analysis)

1ļøāƒ£ Introduction

Quick Sort is a highly efficient Divide-and-Conquer sorting algorithm.

šŸ”¹ Idea

  • Select a pivot element
  • Partition the array into:
    • Elements less than pivot
    • Elements greater than pivot
  • Recursively sort the partitions

It is widely used due to its excellent average-case performance.


2ļøāƒ£ Working Principle (Divide & Conquer)

šŸ”¹ Steps

  1. Divide: Choose a pivot and partition the array
  2. Conquer: Recursively apply Quick Sort on subarrays
  3. Combine: No extra work needed (already sorted in place)

3ļøāƒ£ Algorithm (Quick Sort)

šŸ”¹ Pseudocode

QuickSort(A, low, high):
   if low < high:
       p = Partition(A, low, high)
       QuickSort(A, low, p-1)
       QuickSort(A, p+1, high)

šŸ”¹ Partition Function (Lomuto Method)

Partition(A, low, high):
   pivot = A[high]
   i = low - 1

   for j = low to high-1:
       if A[j] <= pivot:
           i = i + 1
           swap A[i] and A[j]

   swap A[i+1] and A[high]
   return i+1

4ļøāƒ£ Example (Step-by-Step)

šŸ”¹ Given Array:

A = [10, 7, 8, 9, 1, 5]

šŸ”¹ Step 1: Choose Pivot (5)

Partition:

[1, 5, 8, 9, 10, 7]

šŸ”¹ Step 2: Left Subarray [1]

Already sorted


šŸ”¹ Step 3: Right Subarray [8, 9, 10, 7]

Pivot = 7

[7, 8, 9, 10]

šŸ”¹ Final Sorted Array:

[1, 5, 7, 8, 9, 10]

āœ” Sorted successfully


5ļøāƒ£ Running Time Analysis

šŸ”¹ Recurrence Relation

Best / Average Case:

[
T(n) = 2T(n/2) + O(n)
]

Worst Case:

[
T(n) = T(n-1) + O(n)
]


6ļøāƒ£ Time Complexity

CaseComplexity
Best CaseO(n log n)
Average CaseO(n log n)
Worst CaseO(n²)

šŸ‘‰ Worst case occurs when:

  • Array is already sorted
  • Poor pivot selection

7ļøāƒ£ Space Complexity

  • Recursive stack:
    • Best/Average → O(log n)
    • Worst → O(n)

8ļøāƒ£ Recursion Tree Analysis (Concept)

šŸ”¹ Balanced Partition

  • Depth = log n
  • Work per level = n

Total:
[
O(n \log n)
]


šŸ”¹ Unbalanced Partition

  • Depth = n
  • Work per level = n

Total:
[
O(n²)
]


9ļøāƒ£ Characteristics of Quick Sort

āœ” In-place sorting
āœ” Very fast in practice
āœ” Not stable
āœ” Performance depends on pivot


šŸ”Ÿ Advantages

  • Faster than Merge Sort in practice
  • Requires less memory
  • Good cache performance
  • Widely used in real systems

1ļøāƒ£1ļøāƒ£ Disadvantages

  • Worst-case O(n²)
  • Not stable
  • Recursive overhead

1ļøāƒ£2ļøāƒ£ Comparison with Merge Sort

FeatureQuick SortMerge Sort
Time (Avg)O(n log n)O(n log n)
Worst CaseO(n²)O(n log n)
SpaceO(log n)O(n)
StabilityNoYes

šŸ”š Conclusion

Quick Sort is one of the fastest sorting algorithms in practice, especially for large datasets.

Its efficiency depends on good pivot selection, making average performance excellent but worst-case performance poor.


šŸ“Œ Exam Tip

šŸ‘‰ Always include:

  • Partition concept
  • Recurrence relation
  • Time complexity cases
  • Example