function bubbleSort(arr) {
var len = arr.length
for (var i = 0; i < len; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
;[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]
}
}
}
return arr
}
2.2 选择排序
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let min = i
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j
}
}
;[arr[i], arr[min]] = [arr[min], arr[i]]
}
return arr
}
2.3 插入排序
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let preIndex = i - 1
let current = arr[i]
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex]
preIndex--
}
arr[preIndex + 1] = current
}
return arr
}
2.4 归并排序
function mergeSort(arr) {
//采用自上而下的递归方法
var len = arr.length
if (len < 2) {
return arr
}
var middle = Math.floor(len / 2),
left = arr.slice(0, middle),
right = arr.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}
function merge(left, right) {
var result = []
while (left.length && right.length) {
if (left[0] <= right[0]) {
result.push(left.shift())
} else {
result.push(right.shift())
}
}
while (left.length) result.push(left.shift())
while (right.length) result.push(right.shift())
return result
}
2.5 快速排序
function quickSort(arr) {
if (arr.length <= 1) return arr
let midIndex = Math.floor(arr.length / 2)
let mid = arr.splice(midIndex, 1)[0] //找出基准元素
let left = []
let right = []
for (let i of arr) {
if (i > mid) {
right.push(i)
} else {
left.push(i)
}
}
return [...quickSort(left), mid, ...quickSort(right)]
}
参考链接:十大经典算法排序总结对比
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)