js排序的几种方法
一、冒泡排序 冒泡排序就是数组相邻两个元素的对比和位置交换。这个是我们学习代码排序的时候最先学的排序方法。
解析:
1.比较相邻的两个元素,如果前一个比后一个大,则交换位置。
2.第一轮的时候最后一个元素应该是最大的一个。
3.按照步骤一的方法进行相邻两个元素的比较,这个时候由于最后一个元素已经是最大的了,所以最后一个元素 不用比较。
const arr1 = [1, 5, 7, 6, 0, 9, 4];
function maopao(array){
if(Array.isArray(array)){
if (array.length === 1) {
return array;
}
let temp = null;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
}
console.log(maopao(arr1)); // 0,1,4,5,6,7,9
二、sort排序,es6新增的方法
const arr5 = [1, 9, 4, 2, 5, 3, 0, 8, 6, 7, 4, 5, 3, 7, 8];
arr5.sort();
console.log(arr5); // 0,1,2,3,3, 4,4, 5,5, 6,7, 7,8,9
sort去重排序
const list = [...new Set(arr5)]
list.sort();
console.log(arr5); // 0,1,2,3,4,5,6,7,8,9
sort方法优点是代码简单优雅,缺点是只排元素首个字符。
三、选择排序
(1)在未排序序列中找到最小元素,把它放到排序序列起始位置。
(2)从剩余未排序序列中继续寻找最小元素,然后放在排序序列末尾。
(3)以此类推,直至所有元素排序完成。
const arr2 = [1, 4, 2, 0, 3, 8, 6];
function xuanze(array) {
if (Array.isArray(array)) {
if (array.length === 1) {
return array;
}
for (let i = 0; i < array.length - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < array.length; j++) {
if (array[j] > array[minIndex]) {
minIndex = j
}
// minIndex = array[minIndex] < array[j] ? j : minIndex;
}
[array[i],array[minIndex]] = [array[minIndex], array[i]];
}
return array;
}
} console.log(xuanze(arr2)); // 8,6,4,3,2,1,0
四、递归排序(快排)
(1)从数列中取出一个数作为参考,分区过程。
(2)将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
(3)对左右区间重复第二步,直到各区间只有一个数。
const arr3 = [1, 9, 4, 2, 5, 3, 8, 6, 7, 0];
function digui(array) {
if (Array.isArray(array)) {
if (array.length <= 1) {
return array;
}
const centerIndex = Math.ceil(array.length / 2);
const cValue = array.splice(centerIndex, 1);
const left = [];
const right = [];
array.forEach(function (value) {
if (value > cValue) {
left.push(value);
}else {
right.push(value);
}
});
return digui(left).concat(cValue, digui(right));
}
} console.log(digui(arr3)); // 9,8,7,6,5,4,3,2,1,0
五、快速排序
解析:快速排序是对冒泡排序的一种改进,第一趟排序时将数据分成两部分,一部分比另一部分的所有数据都要小。然后递归调用,在两边都实行快速排序。 const array = [5,6,2,1,3,4,7,1.2,8,9];
function quickSort(array) {
if (array.length <= 1){
return array;
}
const pivotIndex = Math.floor(array.length / 2);
const pivot = array.splice(pivotIndex, 1)[0];
const left = [];
const right = [];
for (let i = 0; i < array.length; i++) {
if (array[i] < pivot) {
left.push(array[i]);
} else {
right.push(array[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
} console.log(quickSort(array)) // 1, 1.2, 2, 3, 4, 5, 6, 7, 8, 9