JSFiddle - React, Tailwind, and code Playground

by Derek Anderson

JavaScript

// non comparison radix sort
// for alphabetizing a list

function alphatize(inputArray) {
  var t0 = performance.now();
	// generate array to hold sorting
  function getSortBuckets() {
    return [].concat.apply([], Array(26))
              .map(function(_, i) { return [] });
  }
  
  // sort into buckets
  function sort(arr, iteration) {
  	// setup buckets
  	var buckets = getSortBuckets();
    
    // iterate through 
    for(var itemIndex = 0; itemIndex < arr.length; itemIndex++) { // O(n)
      
  		var item = arr[itemIndex];
      var charIndex =  (item.length - 1) - iteration;
      
      // get the significant values from right to left
      // for now assume 'a'
      // optimize skip checking items that are shorter 
      // there for already alphabetized, split the list
      var significantValue = item.charCodeAt(charIndex) || item.charCodeAt(0);
      
      // use 0-25 so offset the char value
      // determine is usin lowecase, or upper case offset accordingly
      var offset = significantValue > 91 ? 97 : 65;
      
      // using indexes for O(1) access time when getting a bucket
      // vs a map O(n)
      buckets[significantValue - offset].push(item);
    }
    return buckets;
  };
  
	// determine how many iterations we need to do on our alphabetizing
	// O(n)
	var iterations = inputArray.reduce( (a, b) => { return a.length > b.length ? a : b; }).length;

	for(var iteration = 0; iteration < iterations; iteration++) { // O(k) overpowered by O(n)
  	inputArray = [].concat.apply([], sort(inputArray, iteration));
  }
  var t1 = performance.now();
  console.log("Custom radix sort: " + (t1 - t0) + " milliseconds.")
  return inputArray;
};

var list =...