Radix Sort

Let’s do an example…

Java Implementation

  private static void radixSort(int[] numbers, int radix) {
     ArrayList<ArrayList<Integer>> buckets = new ArrayList<ArrayList<Integer>>();
     
     for (int i = 0; i < radix; i++) {
        buckets.add(new ArrayList<Integer>());
     }
     
     int copyBackIndex = 0;
     
     int maxDigits = radixGetMaxLength(numbers, radix);
     
     int pow = 1;
     for (int digitIndex = 0; digitIndex < maxDigits; digitIndex++) {
        for (int num : numbers) {
           int bucketIndex = (Math.abs(num) / pow) % radix;
           buckets.get(bucketIndex).add(num);
        }
        
        // Copy buckets back into numbers array
        copyBackIndex = 0;
        for (int i = 0; i < radix; i++) {
           ArrayList<Integer> bucket = buckets.get(i);
           
           for (int val:  bucket) {
              numbers[copyBackIndex] = val;
              copyBackIndex++;
           }
           
           bucket.clear();
        }
        
        pow *= radix;
     }
  }

What is the run time of this algorithm?

Let’s Look At Some Timing Examples…

Radix Sort… Lessons Learned

Lower Bound on Comparison-Based Sorts