佛山市门户网站建设公司,wordpress通过标签搜索,免费自己制作音乐,搜索引擎是网站吗在JavaScript中#xff0c;有多种排序方式可供选择。以下是几种常见的排序方式以及对应的示例#xff1a; 冒泡排序#xff08;Bubble Sort#xff09;#xff1a; 冒泡排序是一种比较简单的排序算法#xff0c;它重复地比较相邻的两个元素并交换位置#xff0c;直到整个…在JavaScript中有多种排序方式可供选择。以下是几种常见的排序方式以及对应的示例 冒泡排序Bubble Sort 冒泡排序是一种比较简单的排序算法它重复地比较相邻的两个元素并交换位置直到整个数组排序完成。 function bubbleSort(arr) {const len arr.length;for (let i 0; i len - 1; i) {for (let 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;
}const nums [5, 3, 8, 4, 2];
const sortedNums bubbleSort(nums); // [2, 3, 4, 5, 8]插入排序Insertion Sort 插入排序的思想是将数组分为已排序和未排序两部分每次从未排序部分取出一个元素插入到已排序部分的正确位置。 function insertionSort(arr) {const len arr.length;for (let i 1; i len; i) {let current arr[i];let j i - 1;while (j 0 arr[j] current) {arr[j 1] arr[j];j--;}arr[j 1] current;}return arr;
}const nums [5, 3, 8, 4, 2];
const sortedNums insertionSort(nums); // [2, 3, 4, 5, 8]选择排序Selection Sort 选择排序的思想是每次从未排序部分选择最小或最大的元素放到已排序部分的末尾。 function selectionSort(arr) {const len arr.length;for (let i 0; i len - 1; i) {let minIndex i;for (let j i 1; j len; j) {if (arr[j] arr[minIndex]) {minIndex j;}}if (minIndex ! i) {[arr[i], arr[minIndex]] [arr[minIndex], arr[i]]; // 交换位置}}return arr;
}const nums [5, 3, 8, 4, 2];
const sortedNums selectionSort(nums); // [2, 3, 4, 5, 8]快速排序Quick Sort 快速排序是一种常用的排序算法它通过选择一个基准元素将数组划分为左右两个子数组然后递归地对子数组进行排序。 function quickSort(arr) {if (arr.length 1) {return arr;}const pivotIndex Math.floor(arr.length / 2);const pivot arr.splice(pivotIndex, 1)[0];const left [];const right [];for (let i 0; i arr.length; i) {if (arr[i] pivot) {left.push(arr[i]);} else {right.push(arr[i]);}}return quickSort(left).concat([pivot], quickSort(right));
}const nums [5, 3, 8, 4, 2];
const sortedNums quickSort(nums); // [2, 3, 4, 5, 8]这些是几种常见的排序方式和对应的示例。值得注意的是在实际应用中可以根据排序需求和数据规模选择合适的排序算法。另外JavaScript还提供了内置的排序函数Array.prototype.sort()可以直接调用该函数对数组进行排序。