1、选择排序
选择出最小的或者做大的然后两两比较进行排序
let minIndex = (numbers) =>{
let index = 0
for(let i=1;i<numbers.length;i++){
if(numbers[i] < numbers[index]){
index = i
}
}
return index
}
let swap = (array,i,j) =>{
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
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)}
}
return numbers
}
2、快速排序
快速排序 以基准进行比较进行排序
let quicksort = arr =>{
if(arr.length < 2){return arr}
let pivotIndex = Math.floor(arr.lengtn /2)
let pivot =arr.splice(pivotIndex,1)[0]
let left = []
let right = []
for(let i = 0;i<arr.length;i++){
if(arr[i]<pivot){left.push(arr[i])
}else{right.push(arr[i])}
}
return quicksort(left).concat([pivot],quicksort(right))
}
3、归并排序
归并排序,把需要排序的数组进行划分排序,然后将其进行合并
let mergesort = arr =>{
let k = arr.length
if(k===1){return arr}
else{
let left = arr.slice(0,Math.floor(k/2))
let right = arr.slice(Math.floor(k/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))}
//出现错误 代码:b[0].concat(merge(a,b.slice(1))) b[0] !== [b[0]]
4、计数排序
使用哈希表做记录
let countsort = arr =>{
let hashTable = {},max = 0,result = []
for(let i = 0 ;i <arr.length;i++){ //遍历数组
if(!(arr[i] in hashTable)){ // 出现错误 代码if(!arr[i] in hashTable)
hashTable[arr[i]] = 1
}else{
hashTable[arr[i]] += 1
}
if(arr[i]>max) {max = arr[i]}
}
for(let j=0; j<=max;j++){ //遍历哈希表
if(j in hashTable){
for(let i=0;i<hashTable[j];i++){ //若出现多次,遍历哈希表时多次打印
result.push(j)
}
}
}
return result
}
5、冒泡排序
6、插入排序
7、希尔排序
希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
let xier = arr =>{
let len = arr.length;
for (var fraction = Math.floor(len / 2); fraction > 0; fraction = Math.floor(fraction / 2)) {
for (var i = fraction; i < len; i++) {
for (var j = i - fraction; j >= 0 && arr[j] > arr[fraction + j]; j -= fraction) {
var temp = arr[j];
arr[j] = arr[fraction + j];
arr[fraction + j] = temp;
}
}
}
return arr
}
8、基数排序
比较所有数字的个位数、然后比较所有数字的十位数、百位、千位…… 然后进行排序