JavaScript Algorithms: Sort a list using Bubble Sort
function swapElement(arr, firstIndex, secondIndex){
var tmp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = tmp;
}
function bubbleSort(arr){
var len = arr.length,
i, j, stop;
for (i = 0; i < len; i++){
for (j = 0, stop = len-i; j < stop; j++){
if (arr[j] > arr[j+1]){
swapElement(arr, j, j+1);
}
}
}
return arr;
}
console.log(bubbleSort([30, 3, 90, 150, 45, 63, 27, 18, 12, 999]));
no comments