sorting algorithms js code example
Example 1: what is the algorithm for javascript array.sort
function bubbleSort(arr){
var len = arr.length;
for (var i = len-1; i>=0; i--){
for(var j = 1; j<=i; j++){
if(arr[j-1]>arr[j]){
var temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
bubbleSort([7,5,2,4,3,9]);
bubbleSort([9,7,5,4,3,1]);
bubbleSort([1,2,3,4,5,6]);
Example 2: sorting algorithms in node.js
function sort(arr, compareFn = (a, b) => a <= b) {
if (!arr instanceof Array || arr.length === 0) {
return arr;
}
if (typeof compareFn !== 'function') {
throw new Error('compareFn is not a function!');
}
const partition = (arr, low, high) => {
const pivot = arr[low];
while (low < high) {
while (low < high && compareFn(pivot, arr[high])) {
--high;
}
arr[low] = arr[high];
while (low < high && compareFn(arr[low], pivot)) {
++low;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
};
const quickSort = (arr, low, high) => {
if (low < high) {
let pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
return arr;
};
return quickSort(arr, 0, arr.length - 1);
}