一、快排
// 方法一
function quickSort (arr) {
if (arr.length <= 1) {
return arr
}
let pivotKey = Math.floor(arr.length / 2)
let pivotVal = arr[pivotKey]
let left = []
let right = []
for (let i = 0
if (i === pivotKey) {
continue
} if (arr[i] <= pivotVal) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return quickSort(left).concat([pivotVal], quickSort(right))
}
// 方法二
function quickSort2 (arr, start, end) {
if (start >= end) {
return
}
let left = start
let right = end
let pivot = arr[start]
while (left < right) {
while (right > left && arr[right] >= pivot) {
right--
}
while (left < right && arr[left] <= pivot) {
left++
}
[arr[left], arr[right]] = [arr[right], arr[left]]
}
[arr[left], arr[start]] = [arr[start], arr[left]]
quickSort2(arr, start, left-1)
quickSort2(arr, left+1, end)
return arr
}
console.log(quickSort([7,3,4,3,5,6,8,4,9]))
console.log(quickSort([1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(quickSort2([7,3,4,3,5,6,8,4,9], 0, 8))
console.log(quickSort2([1, 2, 3, 4, 5, 6, 7, 8, 9], 0, 8))
二、冒泡排序
function bubbleSort (arr) {
if (arr.length <= 1) {
return arr
}
let blockedLen = arr.length - 1
let pos = 0
for (let i = 0
let isSorted = true
for (let j = 0
if (arr[j] > arr[j+1]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
isSorted = false
pos = j
}
}
blockedLen = pos
if (isSorted) {
return arr
}
}
return arr
}
console.log(bubbleSort([7,3,4,3,5,6,8,4,9]))
console.log(bubbleSort([1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(bubbleSort([1, 3, 2, 5, 4, 6, 7, 8, 9]))
三、选择排序
function selectSort (arr) {
if (arr.length <= 1) {
return arr
}
for (let i = 0
let minNum = i
for (let j = i + 1
if (arr[j] < arr[minNum]) {
minNum = j
}
}
if (minNum !== i) {
[arr[minNum], arr[i]] = [arr[i], arr[minNum]]
}
}
return arr
}
console.log(selectSort([7,3,4,3,5,6,8,4,9]))
console.log(selectSort([1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(selectSort([1, 3, 2, 5, 4, 6, 7, 8, 9]))
四、插入排序
function insertSort (arr) {
if (arr.length <= 1) {
return arr
}
for (let i = 1
let prevIndex = i - 1
let currentVal = arr[i]
while (prevIndex >= 0 && arr[prevIndex] > currentVal) {
arr[prevIndex + 1] = arr[prevIndex]
prevIndex--
}
arr[prevIndex + 1] = currentVal
}
return arr
}
console.log(insertSort([7,3,4,3,5,6,8,4,9]))
console.log(insertSort([1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(insertSort([1, 3, 2, 5, 4, 6, 7, 8, 9]))
五、堆排序
function heapSort (arr) {
if (arr.length <= 1) {
return arr
}
for (let i = Math.floor(arr.length / 2) - 1
adjustMaxHeap(arr, i, arr.length)
}
for (let j = arr.length - 1
[arr[0], arr[j]] = [arr[j], arr[0]]
adjustMaxHeap(arr, 0, j)
}
return arr
}
function adjustMaxHeap (arr, i, len) {
for (let k = 2 * i + 1
if (k + 1 < len && arr[k+1] > arr[k]) {
k++
}
if (arr[k] > arr[i]) {
[arr[k], arr[i]] = [arr[i], arr[k]]
i = k
}
}
}
console.log(heapSort([7,3,4,3,5,6,8,4,9]))
console.log(heapSort([1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(heapSort([1, 3, 2, 5, 4, 6, 7, 8, 9]))