排序算法和折半查找
// 冒泡排序
function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// 快速排序
function quickSort(arr) {
if (arr.length <= 1) return arr;
// 取基准值
let value = arr.splice(~~(arr.length / 2), 1)[0],
leftArr = [],
rightArr = [];
for (let i = 0; i < arr.length; i++) {
value > arr[i] ? leftArr.push(arr[i]) : rightArr.push(arr[i]);
}
return quickSort(leftArr).concat(value, quickSort(rightArr));
}
console.log(quickSort([10, 2, 3, 32, 65]));
// 选择排序
function selectionSort(arr) {
let index;
for (let i = 0; i < arr.length - 1; i++) {
index = i;
for (let j = i + 1; j < arr.length; j++) {
arr[index] > arr[j] && (index = j);
}
index !== i && ([arr[i], arr[index]] = [arr[index], arr[i]]);
}
return arr;
}
console.log(selectionSort([4, 5, 1, 3]));
// 插入排序
function insertionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let j = i,
value = arr[i];
while (j > 0 && arr[j - 1] > value) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = value;
}
return arr;
}
console.log(insertionSort([4, 3, 32, 76, 1]));
// 二分查找
function binarySearch(target, arr, start, end) {
if (start > end) return -1;
let midIndex = ~~((start + end) / 2);
if (target === arr[midIndex]) {
return midIndex;
} else if (target < arr[midIndex]) {
return binarySearch(target, arr, start, midIndex - 1);
} else {
return binarySearch(target, arr, midIndex + 1, end);
}
}
console.log(binarySearch(2, [1, 2, 3, 4, 5], 0, 4));