1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Quick Sort
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
20Hrs
35Mins
07Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Quick Sort

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
20Hrs
35Mins
07Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Quick Sort

Overview

Quick Sort is another Divide and Conquer algorithm, but it takes the opposite approach of Merge Sort. Instead of doing the heavy lifting during the 'merge', Quick Sort does the heavy lifting during the 'divide'.

It works by selecting a Pivot element from the array. It then 'Partitions' the array: it physically moves every element smaller than the pivot to the left of the pivot, and every element larger to the right. Once partitioned, the pivot is guaranteed to be in its absolute final sorted position! It then recursively applies this process to the left and right sub-arrays.

Quick Sort is highly prized because it operates In-Place (O(1) auxiliary array space, though O(log N) stack space) and has incredible cache-locality, making it faster than Merge Sort in practical, real-world benchmarks. However, if poorly implemented, its worst-case time complexity degrades to a catastrophic O(N^2).

Syntax

The Partition Logic
java
public class QuickSort {
    public static void sort(int[] arr, int left, int right) {
        if (left < right) {
            // Partition the array and get the pivot's final sorted index
            int pivotIndex = partition(arr, left, right);
            
            // Recursively sort the left and right sides
            sort(arr, left, pivotIndex - 1);
            sort(arr, pivotIndex + 1, right);
        }
    }
    
    // Lomuto Partition Scheme
    private static int partition(int[] arr, int left, int right) {
        // Choose the last element as the pivot
        int pivot = arr[right]; 
        int i = left - 1; // Index of smaller element
        
        for (int j = left; j < right; j++) {
            // If current element is smaller than the pivot
            if (arr[j] < pivot) {
                i++;
                // Swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        
        // Finally, swap the pivot into its correct place (i + 1)
        int temp = arr[i + 1];
        arr[i + 1] = arr[right];
        arr[right] = temp;
        
        return i + 1; // Return the pivot's new permanent index
    }
}

Common Pitfalls

  • The O(N^2) Worst-Case Nightmare. If you always pick the last element as the pivot, and the array is already sorted, Quick Sort won't divide the array in half. It will peel off exactly one element per recursive call. This causes O(N) recursive depth and O(N) scanning per level, resulting in O(N^2) time and StackOverflow crashes.
  • Failing to randomize the pivot. To prevent the O(N^2) worst-case from being triggered by malicious input or sorted data, modern implementations pick a random element as the pivot, or use the 'Median of Three' method.
  • Instability. Unlike Merge Sort, Quick Sort is NOT stable. The heavy swapping during the partition phase will scramble the relative order of duplicate elements.

Interview Questions

Why is Quick Sort generally preferred over Merge Sort for Arrays, even though it has a worse theoretical worst-case?

Two reasons: Memory and Cache Locality. Quick Sort sorts 'In-Place', saving massive amounts of RAM (no O(N) temp arrays). Furthermore, because it sequentially scans and swaps elements directly in a single contiguous array block, it works perfectly with modern CPU L1/L2 caches, resulting in raw execution speeds far faster than Merge Sort.

What is QuickSelect?

QuickSelect is a modification of Quick Sort used to find the Kth smallest/largest element in an array in O(N) time. Instead of recursively sorting both sides of the pivot, you check the pivot's final index. If it is K, you are done! If K is smaller, you only recurse on the left half. It throws away half the array at each step.

Real-World Example

Java's default Arrays.sort(primitiveArray) uses Dual-Pivot QuickSort. Instead of choosing one pivot and splitting the array into two zones (less than, greater than), it chooses two pivots and splits the array into three zones. This mathematically reduces the depth of recursion and speeds up processing significantly.

example
java
// Under the hood in java.util.Arrays (simplified concept)
public static void sort(int[] a) {
    DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}

Check Your Knowledge

Test your understanding of Quick Sort with these quick questions.

Question 1

What is the job of the 'Partition' step in Quick Sort?

Question 2

What triggers the catastrophic O(N^2) worst-case in a naive Quick Sort?

Question 3

Does Quick Sort require O(N) auxiliary space like Merge Sort?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Quick Sort

Overview

Quick Sort is another Divide and Conquer algorithm, but it takes the opposite approach of Merge Sort. Instead of doing the heavy lifting during the 'merge', Quick Sort does the heavy lifting during the 'divide'.

It works by selecting a Pivot element from the array. It then 'Partitions' the array: it physically moves every element smaller than the pivot to the left of the pivot, and every element larger to the right. Once partitioned, the pivot is guaranteed to be in its absolute final sorted position! It then recursively applies this process to the left and right sub-arrays.

Quick Sort is highly prized because it operates In-Place (O(1) auxiliary array space, though O(log N) stack space) and has incredible cache-locality, making it faster than Merge Sort in practical, real-world benchmarks. However, if poorly implemented, its worst-case time complexity degrades to a catastrophic O(N^2).

Syntax

The Partition Logic
java
public class QuickSort {
    public static void sort(int[] arr, int left, int right) {
        if (left < right) {
            // Partition the array and get the pivot's final sorted index
            int pivotIndex = partition(arr, left, right);
            
            // Recursively sort the left and right sides
            sort(arr, left, pivotIndex - 1);
            sort(arr, pivotIndex + 1, right);
        }
    }
    
    // Lomuto Partition Scheme
    private static int partition(int[] arr, int left, int right) {
        // Choose the last element as the pivot
        int pivot = arr[right]; 
        int i = left - 1; // Index of smaller element
        
        for (int j = left; j < right; j++) {
            // If current element is smaller than the pivot
            if (arr[j] < pivot) {
                i++;
                // Swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        
        // Finally, swap the pivot into its correct place (i + 1)
        int temp = arr[i + 1];
        arr[i + 1] = arr[right];
        arr[right] = temp;
        
        return i + 1; // Return the pivot's new permanent index
    }
}

Common Pitfalls

  • The O(N^2) Worst-Case Nightmare. If you always pick the last element as the pivot, and the array is already sorted, Quick Sort won't divide the array in half. It will peel off exactly one element per recursive call. This causes O(N) recursive depth and O(N) scanning per level, resulting in O(N^2) time and StackOverflow crashes.
  • Failing to randomize the pivot. To prevent the O(N^2) worst-case from being triggered by malicious input or sorted data, modern implementations pick a random element as the pivot, or use the 'Median of Three' method.
  • Instability. Unlike Merge Sort, Quick Sort is NOT stable. The heavy swapping during the partition phase will scramble the relative order of duplicate elements.

Interview Questions

Why is Quick Sort generally preferred over Merge Sort for Arrays, even though it has a worse theoretical worst-case?

Two reasons: Memory and Cache Locality. Quick Sort sorts 'In-Place', saving massive amounts of RAM (no O(N) temp arrays). Furthermore, because it sequentially scans and swaps elements directly in a single contiguous array block, it works perfectly with modern CPU L1/L2 caches, resulting in raw execution speeds far faster than Merge Sort.

What is QuickSelect?

QuickSelect is a modification of Quick Sort used to find the Kth smallest/largest element in an array in O(N) time. Instead of recursively sorting both sides of the pivot, you check the pivot's final index. If it is K, you are done! If K is smaller, you only recurse on the left half. It throws away half the array at each step.

Real-World Example

Java's default Arrays.sort(primitiveArray) uses Dual-Pivot QuickSort. Instead of choosing one pivot and splitting the array into two zones (less than, greater than), it chooses two pivots and splits the array into three zones. This mathematically reduces the depth of recursion and speeds up processing significantly.

example
java
// Under the hood in java.util.Arrays (simplified concept)
public static void sort(int[] a) {
    DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}

Check Your Knowledge

Test your understanding of Quick Sort with these quick questions.

Question 1

What is the job of the 'Partition' step in Quick Sort?

Question 2

What triggers the catastrophic O(N^2) worst-case in a naive Quick Sort?

Question 3

Does Quick Sort require O(N) auxiliary space like Merge Sort?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A