Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Radix Sort Algorithm in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Radix Sort Algorithm
Find max number to know max digits
↓
For each digit from LSD to MSD
↓
Place numbers into buckets by current digit
↓
Collect numbers from buckets in order
↓
Repeat for next digit
↓
Sorted array ready
Radix sort processes digits from least to most significant, grouping numbers by each digit, then collecting them back in order, repeating until fully sorted.
Execution Sample
DSA Javascript
function radixSort(arr) {
  let max = Math.max(...arr);
  let exp = 1;
  while (Math.floor(max / exp) > 0) {
    arr = countingSortByDigit(arr, exp);
    exp *= 10;
  }
  return arr;
}
Sorts an array of numbers by processing each digit from least significant to most significant using counting sort.
Execution Table
StepOperationCurrent Digit (exp)Buckets (0-9)Array After CollectionVisual State
1Find max number---[170, 45, 75, 90, 802, 24, 2, 66]
2Process digit exp=1 (units place)1
0: 170, 90
1:
2: 802, 2
3:
4: 24
5: 45, 75
6: 66
7:
8:
9:
[170, 90, 802, 2, 24, 45, 75, 66][170, 90, 802, 2, 24, 45, 75, 66]
3Process digit exp=10 (tens place)10
0: 802, 2
1:
2: 24
3:
4: 45
5:
6: 66
7: 170, 75
8:
9: 90
[802, 2, 24, 45, 66, 170, 75, 90][802, 2, 24, 45, 66, 170, 75, 90]
4Process digit exp=100 (hundreds place)100
0: 2, 24, 45, 66, 75, 90
1: 170
2:
3:
4:
5:
6:
7:
8: 802
9:
[2, 24, 45, 66, 75, 90, 170, 802][2, 24, 45, 66, 75, 90, 170, 802]
5Check next digit exp=10001000--Stop: max/exp=0, sorting complete
💡 When max/exp becomes 0 (1000), no more digits to process, sorting ends.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
arr[170, 45, 75, 90, 802, 24, 2, 66][170, 90, 802, 2, 24, 45, 75, 66][802, 2, 24, 45, 66, 170, 75, 90][2, 24, 45, 66, 75, 90, 170, 802][2, 24, 45, 66, 75, 90, 170, 802]
exp11010010001000
max802802802802802
Key Moments - 3 Insights
Why do we start sorting from the least significant digit (units place)?
Because radix sort relies on stable sorting at each digit level, starting from the least significant digit ensures that the order of digits processed earlier is preserved, as shown in steps 2 and 3 where the array is reordered by units then tens digits.
What happens if numbers have different digit lengths?
Shorter numbers are treated as having leading zeros in higher digit places, so they go into bucket 0 for those digits, as seen in step 4 where numbers like 2 and 24 fall into bucket 0 for the hundreds place.
Why do we stop when max/exp becomes 0?
Because it means we have processed all digit places of the largest number, so no further sorting is needed, as indicated in step 5 where max/exp=0 stops the loop.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at Step 3, which bucket contains the number 170?
ABucket 0
BBucket 1
CBucket 7
DBucket 9
💡 Hint
Check the 'Buckets (0-9)' column at Step 3 for where 170 is placed.
At which step does the array first become sorted by the hundreds digit?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Current Digit (exp)' and 'Array After Collection' columns to see when hundreds place sorting happens.
If the maximum number was 99 instead of 802, how many steps would the sorting loop run?
A1
B2
C3
D4
💡 Hint
Check the 'exp' variable changes and when max/exp becomes 0 in the variable_tracker.
Concept Snapshot
Radix Sort Algorithm:
- Sorts numbers digit by digit from least to most significant
- Uses buckets (0-9) for each digit
- Collects numbers after each digit sorting
- Repeats until all digits processed
- Stable and efficient for fixed digit lengths
Full Transcript
Radix sort finds the largest number to know how many digits to process. It starts sorting from the least significant digit (units place), placing numbers into buckets based on that digit. Then it collects numbers back in order. This repeats for tens, hundreds, and so on until all digits are processed. The array becomes sorted after the last digit is handled. The process stops when the digit place exceeds the largest number's digits. This method works well because it sorts numbers by each digit without comparing whole numbers directly.

Practice

(1/5)
1. What is the main idea behind the Radix Sort Algorithm?
easy
A. Sort numbers by swapping adjacent elements repeatedly
B. Sort numbers by comparing each pair directly
C. Sort numbers by dividing them into two halves recursively
D. Sort numbers digit by digit starting from the least significant digit

Solution

  1. Step 1: Understand Radix Sort approach

    Radix Sort sorts numbers by processing each digit separately, starting from the least significant digit (rightmost).
  2. Step 2: Compare with other sorting methods

    Unlike comparison-based sorts, Radix Sort groups numbers by digits without direct comparisons between whole numbers.
  3. Final Answer:

    Sort numbers digit by digit starting from the least significant digit -> Option D
  4. Quick Check:

    Radix Sort = Digit by digit sorting [OK]
Hint: Radix Sort processes digits from right to left [OK]
Common Mistakes:
  • Thinking Radix Sort compares whole numbers directly
  • Confusing Radix Sort with quicksort or mergesort
  • Assuming it sorts from most significant digit first
2. Which of the following is the correct way to initialize a bucket array for Radix Sort in JavaScript?
easy
A. const buckets = [].map(() => []);
B. const buckets = new Array(10).fill([]);
C. const buckets = Array.from({ length: 10 }, () => []);
D. const buckets = Array(10).fill(null);

Solution

  1. Step 1: Understand bucket initialization

    We need 10 separate arrays (buckets) for digits 0-9. Using Array.from with a function creates independent arrays.
  2. Step 2: Why other options fail

    const buckets = new Array(10).fill([]); fills with the same array reference, causing all buckets to share one array. const buckets = [].map(() => []); fails because map on empty array does nothing. const buckets = Array(10).fill(null); fills with null, not arrays.
  3. Final Answer:

    const buckets = Array.from({ length: 10 }, () => []); -> Option C
  4. Quick Check:

    Use Array.from with function for separate buckets [OK]
Hint: Use Array.from with arrow function for unique buckets [OK]
Common Mistakes:
  • Using fill([]) creates shared references
  • Using map on uninitialized array returns empty
  • Filling buckets with null instead of arrays
3. What will be the output of the following JavaScript code snippet using Radix Sort on the array [170, 45, 75, 90, 802, 24, 2, 66]?
function getDigit(num, place) {
  return Math.floor(Math.abs(num) / Math.pow(10, place)) % 10;
}

function radixSort(arr) {
  let maxDigit = Math.floor(Math.log10(Math.max(...arr))) + 1;
  for (let k = 0; k < maxDigit; k++) {
    let buckets = Array.from({ length: 10 }, () => []);
    for (let num of arr) {
      buckets[getDigit(num, k)].push(num);
    }
    arr = [].concat(...buckets);
  }
  return arr;
}

console.log(radixSort([170, 45, 75, 90, 802, 24, 2, 66]));
medium
A. [170, 45, 75, 90, 802, 24, 2, 66]
B. [2, 24, 45, 66, 75, 90, 170, 802]
C. [802, 170, 90, 75, 66, 45, 24, 2]
D. [2, 24, 45, 66, 75, 170, 90, 802]

Solution

  1. Step 1: Understand digit extraction and sorting

    The code sorts numbers by each digit from least significant (units) to most significant. After each pass, numbers are grouped by that digit.
  2. Step 2: Trace sorting passes

    After sorting by units digit, then tens, then hundreds, the array becomes fully sorted ascending: [2, 24, 45, 66, 75, 90, 170, 802].
  3. Final Answer:

    [2, 24, 45, 66, 75, 90, 170, 802] -> Option B
  4. Quick Check:

    Radix Sort output = Sorted ascending array [OK]
Hint: Radix Sort outputs sorted array ascending [OK]
Common Mistakes:
  • Confusing original array with sorted output
  • Misunderstanding digit extraction order
  • Assuming sorting is descending
4. Identify the bug in this Radix Sort snippet and choose the correct fix:
function radixSort(arr) {
  let maxDigit = Math.floor(Math.log10(Math.max(...arr))) + 1;
  for (let k = 0; k <= maxDigit; k++) {
    let buckets = Array.from({ length: 10 }, () => []);
    for (let num of arr) {
      buckets[Math.floor(num / Math.pow(10, k)) % 10].push(num);
    }
    arr = [].concat(...buckets);
  }
  return arr;
}
medium
A. Change loop condition to k < maxDigit instead of <= maxDigit
B. Initialize buckets with new Array(10).fill([])
C. Use Math.ceil instead of Math.floor for maxDigit
D. Remove Math.abs from digit calculation

Solution

  1. Step 1: Analyze loop range for digit passes

    The loop runs from 0 to maxDigit inclusive, causing one extra pass beyond needed digits.
  2. Step 2: Fix loop condition

    Changing k <= maxDigit to k < maxDigit ensures exactly maxDigit passes, avoiding unnecessary iteration.
  3. Final Answer:

    Change loop condition to k < maxDigit instead of <= maxDigit -> Option A
  4. Quick Check:

    Loop runs maxDigit times, not maxDigit+1 [OK]
Hint: Loop digits from 0 to less than maxDigit [OK]
Common Mistakes:
  • Using <= causes extra unnecessary pass
  • Initializing buckets incorrectly with shared arrays
  • Changing floor to ceil breaks digit count
5. You want to use Radix Sort to sort an array containing both positive and negative integers, like [170, -45, 75, -90, 802, 24, -2, 66]. Which approach correctly adapts Radix Sort for this case?
hard
A. Separate negative and positive numbers, sort positives with Radix Sort, sort negatives by absolute value then reverse, then combine
B. Apply Radix Sort directly on all numbers including negatives without changes
C. Convert all numbers to strings and sort lexicographically
D. Use Radix Sort only on positive numbers and ignore negatives

Solution

  1. Step 1: Understand Radix Sort limitation

    Radix Sort works only on non-negative integers because it sorts digits from least significant to most significant.
  2. Step 2: Adapt for negatives

    Separate negatives and positives. Sort positives normally. For negatives, sort their absolute values, then reverse the result to get correct order. Finally, combine negatives (in reversed order) before positives.
  3. Final Answer:

    Separate negative and positive numbers, sort positives with Radix Sort, sort negatives by absolute value then reverse, then combine -> Option A
  4. Quick Check:

    Separate negatives and positives, sort separately [OK]
Hint: Sort negatives by absolute then reverse, positives normally [OK]
Common Mistakes:
  • Trying to sort negatives directly with Radix Sort
  • Ignoring negative numbers in sorting
  • Sorting numbers as strings causing wrong order
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