- 选择排序,时间复杂度:O()
- 快速排序,时间复杂度:O()
- 归并排序,时间复杂度:O()
- 计数排序,时间复杂度:O()
选择排序
```javascript
/
选择排序的递归写法
/
let selectionSort = (arr) => {
if (arr.length > 2) {//let min = Math.min.apply(null,arr)
//let minIndex = arr.indexOf(min)
let min = arr[0]
let minIndex = 0
for (let i = 0; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i]
minIndex = i
}
}
return arr.splice(minIdex,1).concat(selectionSort(arr))
} else { return arr[0] < arr[1] ? arr : arr.reverse()
}
}
<a name="ZqguH"></a>
## 快速排序
```javascript
/*
快速排序
*/
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 = []
let right = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] >= pivot) {
right.push(arr[i])
} else {
left.push(arr[i])
}
}
return quickSort(left).concat([pivot], quickSort(right))
}
归并排序
/*
归并排序
*/
let mergeSort = (arr) => {
if (arr.length === 1) {
return arr
}
let pivotIndex = Math.floor(arr.length / 2)
let left = arr.slice(0, pivotIndex)
let right = arr.slice(pivotIndex)
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(b.slice(1), a))
: [a[0]].concat(merge(a.slice(1), b))
}
计数排序
/*
计数排序
*/
let countSort =(arr)=>{
let hashTable = {}
let max = arr[0]
let min = arr[0]
let 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]}
if(arr[i] < min){min = 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
}
选择排序(循环写法)
/*
选择排序的循环写法
*/
let min = (numbers)=>{
if(numbers.length > 2)
{return min([numbers[0],min(numbers.slice(1))])
}else{
return Math.min.apply(null,numbers)
}
}
let minIndex = (numbers)=> numbers.indexOf(min(numbers))
let swap =(array,x,y) =>{
let temp = numbers[y]
numbers[y] = numbers[x]
numbers[x] = temp
}
let sort =(numbers)=>{
for ( let i = 0 ; i < numbers.length-1; i++){
console.log(`----`)
console.log(`i: ${i}`)
let index = minIndex(numbers.slice(i))+i
console.log(`index: ${index}`)
console.log(`min: ${numbers[index]}`)
if (numbers[i] > numbers[index]){
swap(numbers,index,i)
}
}
return numbers
}