Tutorialspoint
Problem
Solution
Submissions

Quick Sort

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program that implements the quick sort algorithm. The program should take an unsorted array of integers and sort it in ascending order using the divide-and-conquer strategy with a pivot element.

Example 1
  • Input: array = [10, 7, 8, 9, 1, 5]
  • Output: [1, 5, 7, 8, 9, 10]
  • Explanation:
    • Step 1: Choose last element as pivot (5)
    • Step 2: Partition array - elements smaller than pivot go left, larger go right
    • Step 3: After first partition: [1, 5, 8, 9, 10, 7]
    • Step 4: Recursively apply to subarrays [1] and [8, 9, 10, 7]
    • Step 5: Continue until all subarrays are sorted
    • Step 6: Return sorted array [1, 5, 7, 8, 9, 10]
Example 2
  • Input: array = [9, 8, 7, 6, 5, 4, 3, 2, 1]
  • Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  • Explanation:
    • Step 1: Choose last element as pivot (1)
    • Step 2: Partition array - all elements are larger than pivot
    • Step 3: After first partition: [1, 9, 8, 7, 6, 5, 4, 3, 2]
    • Step 4: Recursively apply to subarray [9, 8, 7, 6, 5, 4, 3, 2]
    • Step 5: Continue until all subarrays are sorted
    • Step 6: Return sorted array [1, 2, 3, 4, 5, 6, 7, 8, 9]
Constraints
  • 1 ≤ array.length ≤ 10^5
  • -10^6 ≤ array[i] ≤ 10^6
  • Time Complexity: O(n log n) average case, O(n²) worst case, where n is the length of the array
  • Space Complexity: O(log n) for the recursive call stack
ArraysControl StructuresAlgorithmsDeloitteZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Choose a pivot element from the array (typically the last element).
  • Partition the array around the pivot: elements less than the pivot go to the left, elements greater go to the right.
  • Recursively apply the above steps to the sub-arrays.
  • Create a helper function to handle the partitioning process.
  • The base case of the recursion is when the subarray size becomes 1 or 0, which is already sorted.

Steps to solve by this approach:

 Step 1: Implement a partition function that chooses a pivot element.

 Step 2: Rearrange the array so elements smaller than pivot are on left.
 Step 3: Move elements greater than pivot to the right of pivot.
 Step 4: Return the pivot's final position after partitioning.
 Step 5: Apply recursive quicksort to the left partition.
 Step 6: Apply recursive quicksort to the right partition.
 Step 7: Base case: arrays with 0 or 1 elements are already sorted.

Submitted Code :