JavaScript-排序

Posted by Leo on 2019-07-23

排序

1.0 冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  function sort(arr){
const len = arr.length;
if (len<= 1) {return arr;}
for (let i = 0; i <len - 1 ; i++) {
let hasChange = false;
for (let j = 0; j < len-1-i; j++) {
if (arr[j] > arr[j+1]) {
const temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
hasChange = true;
}
}
if (!hasChange) {break;}
}
console.log(arr);
}
console.log (sort([1,33,55,0,12,33,77]));
0: 0
1: 1
2: 12
3: 33
4: 33
5: 55
6: 77

2.0 快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function quickSort(arr){
let left = [];
let right = [];
var base = arr[arr.length - 1];
if (arr.length <= 1) {return arr};
for (let i = 0; i < arr.length-1; i++) {
if (arr[i] < base) {
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
return [...quickSort(left),...[base],...quickSort(right)];
}
console.log (quickSort([1,33,55,0,12,33,77]));//[0, 1, 12, 33, 33, 55, 77]

3.0 选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 function selectSort(arr){
const len = arr.length;
let minIndex, temp;
for (let i = 0; i < len-1; i++) {
minIndex = i;
for (let j = i+1; j< len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
console.log(arr);
}