冒泡排序:
function bubbleSort(arr){let i = arr.length;while(i >0){for(let j = 0; j< i; j++) {let pos = 0;if(arr[j] > arr[j+1]) {pos = j;let temp = arr[j];arr[j] = arr[j+1];arr[j+1] = temp;}}i = pos;}return arr;
}
var arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(bubbleSort(arr));
选择排序:
function selectionSort(arr) {let len = arr.length;let minIndex, temp;for( let i =0; i< len -1; i++){minIndex = i;for(let j = i+1; j< len; j++) {if(arr[j] < arr[minIndex]) {minIndex = j;}}temp = arr[minIndex];arr[minIndex] = arr[i];arr[i] = temp;}return arr;
}
var arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(selectionSort(arr));
插入排序:
function insertSort(arr) {let len = arr.length;for( let i =1; i< len; i++) {let key = arr[i];let j = i-1;while( j >=0 && arr[j] > key) {arr[j+1] = arr[j];j--;}arr[j+1] = key;}return arr
}
var arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48];
console.log(insertSort(arr));
参考 https://github.com/zoro-web/blog/issues/4