minIndex
let minIndex = numbers => {
let index = 0
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] < numbers[index])
index = i
}
return index
}
swap
let swap = (array,i,j) => {
let temp = array[i]
array[i] = array[j]
array[j] = temp
}
sort选择排序
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}`)
if (numbers[index] < numbers[i])
swap(numbers, index, i)
console.log(numbers)
}
return numbers
}
quickSort快速排序
// 以一个数为基准,小的往前,大的往后
let quickSort = numbers => {
if (numbers.length <= 1) return numbers
console.log('-----')
let pivotIndex = Math.floor(numbers.length / 2)
console.log(`baseIndex:${pivotIndex}`)
let pivot = numbers.splice(pivotIndex,1)[0] // splice返回的是数组
console.log(`base:${pivot}`)
let left = []
let right = []
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] < pivot) left.push(numbers[i])
else right.push(numbers[i])
}
console.log(`left:${left}`)
console.log(`right:${right}`)
return quickSort(left).concat([pivot], quickSort(right))
}
merge归并排序
/*
1. 左右分别排好序
2. 合并
*/
let mergeSort = (numbers) => {
let k = numbers.length
if (k === 1) return numbers
let left = numbers.slice(0, Math.floor(k/2)) // slice(0, length)
let right = numbers.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] ?
[a[0]].concat(merge(a.slice(1), b)) :
[b[0]].concat(merge(a, b.slice(1)))
}
count计数排序(最快)
/*
遍历数组
把计数存入哈希表,记录max值
用for循环打印出哈希表里的key
*/
let countSort = numbers => {
let hashTable = {}, result = [], max = 0
for (let i = 0; i < numbers.length; i++) {
if (!(numbers[i] in hashTable)) {
hashTable[numbers[i]] = 1
}else {
hashTable[numbers[i]] += 1
}
if (numbers[i] > max)
max = numbers[i]
}
for (let i = 0; i <= max; i++){
if (i in hashTable)
for (let j = 0; j < hashTable[i]; j++)
result.push(i)
}
return result
}
时间复杂度
选择排序 O(n)
- 第一次对比 n 次,找出最小值
- 第二次对比 n-1次
- ….
- 最后 1 次
总共比较了 1 + 2 + … + n = n(n + 1) / 2次,复杂度为 O(n)
快速排序 O(n*logn)
- 从中间分,小的往左,大的往右,对比了 n/2 * 2次
- 每一半重复1操作, 对比了 n / 4 * 4
- 每一部分重复1操作, 对比了 n / 8 * 8
- 最后一共对比了(n / logn logn) logn = n logn
归并排序 O(n*logn)
- 第一次merge 对比了 n/2 * 2
- 每一半重复1操作, 对比了 n / 4 * 4
- 每一部分重复1操作, 对比了 n / 8 * 8
- 最后一共对比了(n / logn logn) logn = n logn
计数排序 O(n + max)
其他排序
https://visualgo.net/en/sorting