Tutorialspoint
Problem
Solution
Submissions

Quick Sort

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to implement the Quick Sort algorithm to sort an array of integers in ascending order. Quick Sort is a divide-and-conquer algorithm that works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot.

Example 1
  • Input: arr = [64, 34, 25, 12, 22, 11, 90]
  • Output: [11, 12, 22, 25, 34, 64, 90]
  • Explanation:
    • The initial array is [64, 34, 25, 12, 22, 11, 90].
    • Choose pivot (let's say 64), partition array around it.
    • Recursively sort left partition [34, 25, 12, 22, 11] and right partition [90].
    • Continue partitioning and sorting until all elements are in correct order.
    • Final sorted array is [11, 12, 22, 25, 34, 64, 90].
Example 2
  • Input: arr = [5, 2, 8, 1, 9]
  • Output: [1, 2, 5, 8, 9]
  • Explanation:
    • The initial array is [5, 2, 8, 1, 9].
    • Choose pivot (let's say 5), partition array into [2, 1] and [8, 9].
    • Recursively sort left partition [2, 1] to get [1, 2].
    • Recursively sort right partition [8, 9] which is already sorted.
    • Combine results to get [1, 2, 5, 8, 9].
Constraints
  • 1 ≤ arr.length ≤ 1000
  • -1000 ≤ arr[i] ≤ 1000
  • The array may contain duplicate elements
  • Time Complexity: O(n log n) average case, O(n²) worst case
  • Space Complexity: O(log n) due to recursion stack
ArraysAlgorithmsTech MahindraSamsung
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 (commonly the last element)
  • Partition the array so elements smaller than pivot are on the left, larger on the right
  • Recursively apply quicksort to the left and right subarrays
  • Use two pointers technique for efficient partitioning
  • Handle base case when array has 1 or 0 elements
  • Swap elements during partitioning to maintain order

Steps to solve by this approach:

 Step 1: Choose a pivot element from the array (typically the last element).
 Step 2: Partition the array by placing elements smaller than pivot to the left and larger to the right.
 Step 3: Use two pointers to efficiently rearrange elements during partitioning.
 Step 4: Recursively apply quicksort to the left subarray (elements before pivot).
 Step 5: Recursively apply quicksort to the right subarray (elements after pivot).
 Step 6: Handle base case when subarray has 1 or 0 elements (already sorted).
 Step 7: Continue until all subarrays are sorted and the entire array is sorted.

Submitted Code :