In a previous article, I explained how one can use the in-built JavaScript sort()
function. If you would like to know how you can implement your own sort function for numbers in an array, this article is for you. I am going to show you a function that's similar to the 'Quicksort' algorithm where we select a pivot and if we are sorting in ascending order, we send the numbers smaller than the pivot to a sub-array while greater numbers are sent to a different array and we recursively sort the sub-arrays then merge the sorted sub-array values with the pivot in between into one array.
You can create a JS file and name it customSort.js
. Have the following code in it:
function customSort(array, order = 1) {
if (array.length <= 1) {
return array;
}
const pivot = array[0];
const beforePivot = [];
const afterPivot = [];
for (let i = 1; i < array.length; i++) {
if (
(order === 1 && array[i] <= pivot) ||
(order === 0 && array[i] >= pivot)
) {
beforePivot.push(array[i]);
} else {
afterPivot.push(array[i]);
}
}
const sortedBeforePivot = customSort(beforePivot, order);
const sortedAfterPivot = customSort(afterPivot, order);
return sortedBeforePivot.concat(pivot, sortedAfterPivot);
}
const numbers = [5, 3, 8, 1, 2, 9, 4];
console.log(customSort(numbers)); //ascending
console.log(customSort(numbers, 1)); //ascending
console.log(customSort(numbers, 0)); //descending
Our second function parameter (order
) expects a 1 or 0 so that the function can tell whether we want to sort sort in ascending (1) or descending (0) order with the default being ascending order. Also, we can see that the first check in the function is to see if the array contains only one or no items.
You can run the file locally if you have Node.js installed:
node customSort.js
We have seen how you can sort the function using a function that does something similar to the 'Quicksort' algorithm. You can use a different sort algorithm. I may add custom sort functions using different sorting algorithms later on. I may also modify the function to add another check for whether array values are numbers or not or even sort strings later on.