對一個數組進行排序,全部的方法:html
let arr = [48, 35, 18, 45, 12, 68, 33]
複製代碼
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if(arr[j] > arr[j+1]) {
let temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
}
}
}
}
bubbleSort(arr)
// [12, 18, 33, 35, 45, 48, 68]
複製代碼
function sort (arr) {
for(let i = 1; i < arr.length; i++) {
let temp = arr[i]
for (let j = i - 1; j >= 0; j--) {
if(arr[j] > temp) {
arr[j+1] = arr[j]
if(j === 0) arr[j] = temp
} else {
arr[j+1] = temp
break;
}
}
}
}
sort(arr)
// [12, 18, 33, 35, 45, 48, 68]
複製代碼
function quickSort (arr, low, high) {
let i = low
let j = high
let temp = arr[i]
while (i < j) {
while (i < j && arr[j] >= temp) j--;
if (i < j) arr[i++] = arr[j]
while (i < j && arr[i] <= temp) i++;
if (i < j) arr[j--] = arr[i]
}
arr[i] = temp
if (low < i - 1) quickSort(arr, low, i-1)
if (high > i + 1) quickSort(arr, i+1, high)
}
quickSort(arr, 0, arr.length-1)
// [12, 18, 33, 35, 45, 48, 68]
複製代碼
function mergeSort(arr) {
if (arr.length < 2) return arr
let mid = arr.length >> 1
// 將數組分解成兩邊
let left = arr.slice(0,mid)
left = mergeSort(left)
let right = arr.slice(mid, arr.length)
right = mergeSort(right)
// 合併數組
return merge(left, right)
}
function merge (l, r) {
let len = l.length + r.length
let res = []
let lindex = 0
let rindex = 0
// 遍歷,把小的放進數組裏
for (let i = 0; i < len; i++) {
if(lindex < l.length && rindex < r.length) {
if (l[lindex] <= r[rindex]) {
res.push(l[lindex++])
} else {
res.push(r[rindex++])
}
} else if (lindex >= l.length) {
res.push(r[rindex++])
} else {
res.push(l[lindex++])
}
}
return res
}
const arr1 = mergeSort(arr)
// [12, 18, 33, 35, 45, 48, 68]
複製代碼