选择排序
let sort = (numbers) => {
for(let i=0; i< numbers.length -1;i++){
let index = minIndex(numbers.slice(i))+ i //数组中的最小值,在原数组中对应的下标
if(index!==i){swap(numbers,index,i)} //把第i个和最小的交换
}
return numbers
}
//辅助函数,交换一个数组里面两个元素
let swap = (array,i,j) => {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
//辅助函数,找到一个数组里的最小值的下标
let minIndex = (numbers) => {
let index = 0
for(let i=1; i<numbers.length; i++){
if(numbers[i] < numbers[index]){
index = i
}
}
return index
}
快速排序
let quickSort = arr => { if (arr.length <= 1) { return arr; } //如果数组就一个元素,就不用快排了
let pivotIndex = Math.floor(arr.length / 2); //把数组中间的那个元素作为基准
let pivot = arr.splice(pivotIndex,1)[0]; //从数组中删去基准元素,得到返回值就是基准元素
let left =[]; //定义一个空数组left
let right = []; //定义一个空数组right
for (let i = 0;i < arr.length; i++) { //遍历除去了基准元素的那个数组,比基准元素小的就放到left,否则放到right
if (arr[i] < pivot) {left.push(arr[i])} else { right.push(arr[i]) } } //最后返回一个数组:left数组+基准元素+right数组
return quickSort(left).concat(
[pivot], quickSort(right)) }
归并排序
let mergeSort = arr => {
//如果数组中就一个元素直接返回该数组
if (arr.length === 1) {return arr;}
//数组中有两个及以上元素,那就把这些元素分左右两个数组
let left = arr.slice(0, Math.floor(arr.length / 2));
let right = arr.slice(Math.floor(arr.length / 2));
//再把左右两个数组再分为
return merge(mergeSort(left), mergeSort(right));
};
let merge = (a, b) => {
if (a.length === 0) return b;
if (b.length === 0) return a;
return a[0] > b[0]
? [b[0]].concat(merge(a, b.slice(1)))
: [a[0]].concat(merge(a.slice(1), b));
};
计数排序
let countSort = arr => {
let hashTable = {}, max = 0,result = [];
//遍历数组
for (let i =0; i < arr.length;i++){
if (!(arr[i] in hashTable)) {
hashTable[arr[i]] = 1;
} else {
hashTable[arr[i]] += 1;
}
if (arr[i]>max){
max = arr[i]
}
}//遍历0到最大数
for (let j =0; j<=max;j++){
if (j in hashTable){
for(let i = 0; i < hashTable[j];i++){
result.push(j);
}
}
}
return result;
}