Bird
Raised Fist0
DSA Javascriptprogramming

Quick Sort Algorithm in DSA Javascript

Choose your learning style10 modes available
Mental Model
Quick Sort splits the list into smaller parts around a pivot, sorting each part separately until the whole list is sorted.
Analogy: Imagine sorting a pile of books by picking one book as a reference, then putting all smaller books on one side and bigger books on the other, and repeating this for each side until all books are in order.
Array: [7, 2, 5, 3, 9]
Pivot chosen: 5
Partitioned: [2, 3] -> 5 -> [7, 9]
Dry Run Walkthrough
Input: array: [7, 2, 5, 3, 9]
Goal: Sort the array in ascending order using Quick Sort
Step 1: Choose pivot 9 (last element), partition array
[7, 2, 5, 3, 9]
Why: Pivot divides array into smaller and bigger parts
Step 2: Partition around 9: all elements less than 9 stay left
[7, 2, 5, 3, 9]
Why: All elements are less than 9, so 9 is placed at the end
Step 3: Recursively quick sort left part [7, 2, 5, 3]
[7, 2, 5, 3]
Why: Sort smaller part to fully sort array
Step 4: Choose pivot 3, partition [7, 2, 5, 3]
[7, 2, 5, 3]
Why: Pivot 3 separates smaller and bigger elements
Step 5: Partition around 3: elements less than 3 to left
[2] -> 3 -> [5, 7]
Why: 2 is less than 3, 5 and 7 are greater
Step 6: Recursively quick sort right part [5, 7]
[5, 7]
Why: Sort remaining unsorted part
Step 7: Choose pivot 7, partition [5, 7]
[5, 7]
Why: Pivot 7 separates smaller and bigger elements
Step 8: Partition around 7: 5 is smaller, so 7 placed after 5
[5] -> 7
Why: 5 is smaller than 7, so placed before
Step 9: Combine all parts: [2, 3, 5, 7, 9]
[2, 3, 5, 7, 9]
Why: All parts sorted and combined
Result:
2 -> 3 -> 5 -> 7 -> 9
Annotated Code
DSA Javascript
class QuickSort {
  static partition(arr, low, high) {
    const pivot = arr[high];
    let i = low - 1;
    for (let j = low; j < high; j++) {
      if (arr[j] <= pivot) {
        i++;
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
    }
    [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]];
    return i + 1;
  }

  static quickSort(arr, low, high) {
    if (low < high) {
      const pi = QuickSort.partition(arr, low, high);
      QuickSort.quickSort(arr, low, pi - 1);
      QuickSort.quickSort(arr, pi + 1, high);
    }
  }
}

const arr = [7, 2, 5, 3, 9];
QuickSort.quickSort(arr, 0, arr.length - 1);
console.log(arr.join(' -> '));
const pivot = arr[high];
Select pivot as last element to divide array
for (let j = low; j < high; j++) { if (arr[j] <= pivot) { i++; swap arr[i] and arr[j]; } }
Partition elements: move smaller or equal elements to left side
swap arr[i + 1] and arr[high]; return i + 1;
Place pivot in correct sorted position
if (low < high) { quickSort left part; quickSort right part; }
Recursively sort subarrays around pivot
OutputSuccess
2 -> 3 -> 5 -> 7 -> 9
Complexity Analysis
Time: O(n log n) average case because the array is divided roughly in half each time and each element is compared once per level
Space: O(log n) due to recursive call stack depth in average case
vs Alternative: Better than simple sorting like bubble sort O(n^2) because it reduces problem size quickly by partitioning
Edge Cases
empty array
No sorting needed, returns immediately
DSA Javascript
if (low < high) {
array with one element
No sorting needed, returns immediately
DSA Javascript
if (low < high) {
array with all equal elements
Partitions but no swaps needed, returns sorted array
DSA Javascript
if (arr[j] <= pivot) {
When to Use This Pattern
When you need to sort an array efficiently by dividing and conquering, look for Quick Sort pattern because it sorts by partitioning around pivots.
Common Mistakes
Mistake: Choosing pivot incorrectly or not swapping pivot to correct position
Fix: Always select pivot as last element and swap it to its correct place after partitioning
Mistake: Not updating pointers correctly during partition
Fix: Increment i only when swapping smaller elements to left
Summary
Quick Sort sorts an array by dividing it around a pivot and sorting each part recursively.
Use Quick Sort when you want an efficient average-case sorting algorithm for arrays.
The key insight is partitioning the array around a pivot so smaller elements go left and bigger go right.

Practice

(1/5)
1. What is the main idea behind the Quick Sort algorithm?
easy
A. Sort the array by repeatedly selecting the smallest element
B. Compare every element with every other element and swap if needed
C. Divide the array into smaller parts using a pivot and sort them recursively
D. Merge two sorted arrays into one sorted array

Solution

  1. Step 1: Understand Quick Sort's approach

    Quick Sort picks a pivot element and divides the array into parts smaller and larger than the pivot.
  2. Step 2: Recursive sorting of parts

    It then sorts these parts by calling itself recursively until the whole array is sorted.
  3. Final Answer:

    Divide the array into smaller parts using a pivot and sort them recursively -> Option C
  4. Quick Check:

    Quick Sort = Divide and conquer [OK]
Hint: Remember: pivot divides array, then sort parts recursively [OK]
Common Mistakes:
  • Thinking Quick Sort compares all pairs directly
  • Confusing Quick Sort with Selection Sort
  • Believing Quick Sort merges arrays like Merge Sort
2. Which of the following is the correct syntax to swap two elements arr[i] and arr[j] in JavaScript during Quick Sort?
easy
A. arr[i], arr[j] = arr[j], arr[i];
B. temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
C. swap(arr[i], arr[j]);
D. arr[i] = arr[j]; arr[j] = arr[i];

Solution

  1. Step 1: Identify correct swap method in JavaScript

    JavaScript does not support tuple unpacking like Python, so swapping requires a temporary variable.
  2. Step 2: Check each option

    temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; uses a temporary variable to swap correctly. arr[i], arr[j] = arr[j], arr[i]; is Python syntax, swap(arr[i], arr[j]); is undefined, arr[i] = arr[j]; arr[j] = arr[i]; overwrites values incorrectly.
  3. Final Answer:

    temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; -> Option B
  4. Quick Check:

    Swap with temp variable = temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; [OK]
Hint: Use a temp variable to swap in JavaScript [OK]
Common Mistakes:
  • Using Python-style tuple swap in JavaScript
  • Overwriting one element before saving it
  • Calling undefined swap function
3. What will be the output of the following Quick Sort partition step on array [4, 2, 7, 1] with pivot as the last element?
function partition(arr, low, high) {
  let pivot = arr[high];
  let i = low - 1;
  for (let j = low; j < high; j++) {
    if (arr[j] < pivot) {
      i++;
      let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
    }
  }
  let temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;
  return i + 1;
}

let arr = [4, 2, 7, 1];
let pi = partition(arr, 0, arr.length - 1);
console.log(arr);
medium
A. [1, 2, 7, 4]
B. [1, 2, 4, 7]
C. [4, 2, 7, 1]
D. [2, 1, 4, 7]

Solution

  1. Step 1: Trace the partition loop

    Pivot = 1. Loop checks elements less than 1. No elements are less, so i stays at -1.
  2. Step 2: Swap pivot with element at i+1

    Swap arr[0] and arr[3]: 4 and 1 swap places. Array becomes [1, 2, 7, 4].
  3. Final Answer:

    [1, 2, 7, 4] -> Option A
  4. Quick Check:

    Pivot 1 placed at start, others unchanged [OK]
Hint: Pivot swaps with first bigger element after loop [OK]
Common Mistakes:
  • Assuming pivot stays at end
  • Swapping wrong elements after loop
  • Not updating i correctly
4. Identify the error in this Quick Sort partition function:
function partition(arr, low, high) {
  let pivot = arr[low];
  let i = low + 1;
  for (let j = low + 1; j <= high; j++) {
    if (arr[j] <= pivot) {
      let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
      i++;
    }
  }
  let temp = arr[low]; arr[low] = arr[i]; arr[i] = temp;
  return i;
}
medium
A. Loop should start from low, not low + 1
B. Pivot should be arr[high], not arr[low]
C. No error, function is correct
D. Swapping pivot with arr[i] should be with arr[i - 1]

Solution

  1. Step 1: Understand pivot placement

    Pivot is arr[low]. After loop, pivot must be placed at correct position.
  2. Step 2: Check swap of pivot with arr[i]

    Variable i points to next greater element, so pivot should swap with arr[i - 1], not arr[i].
  3. Final Answer:

    Swapping pivot with arr[i] should be with arr[i - 1] -> Option D
  4. Quick Check:

    Pivot swap index off by one [OK]
Hint: Pivot swap index is i-1 after partition loop [OK]
Common Mistakes:
  • Swapping pivot with wrong index
  • Confusing pivot position in array
  • Changing loop start incorrectly
5. Which of the following pivot selection strategies in Quick Sort will result in the most balanced partitions and thus better performance?
hard
A. Choosing the median of first, middle, and last elements as pivot
B. Choosing the first element as pivot
C. Choosing the middle element as pivot
D. Choosing the last element as pivot

Solution

  1. Step 1: Understand pivot selection strategies

    Choosing first or last can lead to worst-case O(n^2) on sorted arrays. Middle element alone may not be representative.
  2. Step 2: Best strategy for balance

    Median-of-three selects a pivot likely closer to the array's true median, promoting balanced partitions and average O(n log n) performance.
  3. Final Answer:

    Choosing the median of first, middle, and last elements as pivot -> Option A
  4. Quick Check:

    Median-of-three pivot = balanced partitions [OK]
Hint: Median-of-three pivot improves balance and speed [OK]
Common Mistakes:
  • Always picking first or last element as pivot
  • Ignoring pivot choice impact on performance
  • Assuming middle element is always best pivot
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard