【算法】JavaScript 必会算法 —— 排序(冒泡、选择、快排、插入、二分插入、希尔、堆、归并、计数、桶、基数)
以下是实现这些排序算法的JavaScript代码示例:
冒泡排序:
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
let temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return arr;
}
选择排序:
function selectionSort(arr) {
let min;
for (let i = 0; i < arr.length - 1; i++) {
min = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
let temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr;
}
快速排序:
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
let pivot = arr[Math.floor((arr.length - 1) / 2)];
let left = [], right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else if (arr[i] > pivot) {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}
插入排序:
function insertionSort(arr) {
let key, j;
for (let i = 1; i < arr.length; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
return arr;
}
二分插入排序:
function binaryInsertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let key = arr[i], left = 0, right = i - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
for (let j = i - 1; j >= left; j--) {
arr[j + 1] = arr[j];
}
if (left !== i) {
arr[left] = key;
}
}
return arr;
}
希尔排序:
function shellSort(arr) {
let gap = arr.length / 2;
while (gap > 0) {
for (let i = gap; i < arr.length; i++) {
let temp = arr[i];
let j = i;
while ((j >= gap) && (arr[j - gap] > temp)) {
评论已关闭