Quicksort ES5

by Bret Lowrey

HTML

<script src="https://wzrd.in/standalone/minimist@latest"></script>
<script src="https://wzrd.in/standalone/expect@latest"></script>
<body>
Running Tests
</body>

JavaScript

function quicksort(arr) {
	if (arr.length === 0) {
  	return [];
  }
  var head = arr.slice(0, 1);
  var tail = arr.slice(1);
  var less = [];
  var more = [];
  for (var i = 0; i < tail.length; i++) {
  	if (tail[i] < head) {
    	less.push(tail[i]);
    } else {
    	more.push(tail[i]);
    }
  }
  arr = quicksort(less)
  	.concat([head])
    .concat(quicksort(more));
  // flatten
  return [].concat.apply([], arr);
}

expect(quicksort([2, 3, 1, 5, 6, 0, -2, 22])).toEqual([ -2, 0, 1, 2, 3, 5, 6, 22 ]);

document.body.innerHTML = 'All tests passed';