let randomArr = []
function random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
for (let i = 0; i < 10; i++) {
randomArr.push(random(1, 100))
}
function bubbleSort(arr) {
console.log("冒泡排序前", arr)
for (let i = arr.length - 1; i > 0; i--) {
for (let j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
const temp = arr[j + 1]
arr[j + 1] = arr[j]
arr[j] = temp
}
}
}
console.log("冒泡排序后", arr)
}
function selectionSort(arr) {
console.log("选择排序前", arr)
for (let i = arr.length - 1; i > 0; i--) {
let maxIndex = 0
for (let j = 1; j <= i; j++) {
if (arr[maxIndex] < arr[j]) {
maxIndex = j
}
}
const temp = arr[i]
arr[i] = arr[maxIndex]
arr[maxIndex] = temp
}
console.log("选择排序后", arr)
}
function buildMaxHeapify(arr, size) {
arr.unshift(null)
const parentIndex = Math.floor((size + 1) / 2)
for (let i = parentIndex; i > 0; i--) {
maxHeapify(arr, i, size + 1)
}
arr.shift()
}
function maxHeapify(arr, parentIndex, size) {
const left = parentIndex * 2
const right = parentIndex * 2 + 1
let maxChild = -1
if (left > size && right > size) {
return
}
if (left <= size && right > size) {
maxChild = left
}
if (left <= size && right <= size) {
maxChild = arr[left] < arr[right] ? right : left
}
if (arr[parentIndex] < arr[maxChild]) {
const temp = arr[parentIndex]
arr[parentIndex] = arr[maxChild]
arr[maxChild] = temp
maxHeapify(arr, maxChild, size)
}
}
function heapSort(arr) {
console.log('堆排序前', arr)
let heapSize = arr.length - 1
while (heapSize > 0) {
buildMaxHeapify(arr, heapSize)
const temp = arr[0]
arr[0] = arr[heapSize]
arr[heapSize] = temp
heapSize -= 1
}
console.log('堆排序后', arr)
}
function insertionSort(arr) {
console.log('插入排序前', arr)
for (let i = 1; i < arr.length; i++) {
for (j = i; j > 0; j--) {
if (arr[j - 1] > arr[j]) {
const temp = arr[j - 1]
arr[j - 1] = arr[j]
arr[j] = temp
} else {
break
}
}
}
console.log('插入排序后', arr)
}
function mergeSort(arr, begin, end) {
if (begin === end - 1) {
return [arr[begin]]
}
const mid = Math.floor((begin + end) / 2)
const left = mergeSort(arr, begin, mid)
const right = mergeSort(arr, mid, end)
let res = []
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
res.push(left.shift())
} else {
res.push(right.shift())
}
}
res = res.concat(left, right)
return res
}
function quickSort(arr, begin, end) {
if (end - begin < 1) {
return
}
const pivot = arr[begin]
const bi = begin
const ei = end
let direction = -1
while (begin < end) {
if (direction === -1) {
if (arr[end] > pivot) {
end--
} else {
arr[begin] = arr[end]
begin++
direction = 0
}
} else {
if (arr[begin] > pivot) {
arr[end] = arr[begin]
end--
direction = -1
} else {
begin++
}
}
}
arr[begin] = pivot
quickSort(arr, bi, begin)
quickSort(arr, begin + 1, ei)
}