冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function bubbleSort(arr) {
let len = arr.length;
for (let i = 0; i < len; 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]];
console.log(arr);
}
}
}
console.log(arr);
}

bubbleSort([2, 5, 9, 3, 6, 8, 7, 1]);

let text = '10 8 3 2 2 4 9 5 4 3';

let result = text.split(' ').map( (value) => parseInt(value));

console.log(bubbleSort(result));
console.log(result,text);

选择排序

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* https://www.cnblogs.com/Unknw/p/6346681.html
*/
function selectionSort(arr) {
let len = arr.length,
min_index;
for (let i = 0; i < len - 1; i++) {
min_index = i;
for (let j = i + 1; j < len; j++) {
if (arr[min_index] > arr[j]) { // 寻找最小的数
min_index = j; // 将最小数的索引保存
}
}
[arr[i], arr[min_index]] = [arr[min_index], arr[i]];
}
console.log(arr);
return arr;
}

function selectionSort1(arr) {
let len = arr.length;
let minIndex, temp;
for (let i = 0; i < len - 1; i++) {
minIndex = i;
for (let j = i + 1; j < len; j++) { // TODO i + 1
if (arr[j] < arr[minIndex]) { //寻找最小的数
minIndex = j; //将最小数的索引保存
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
console.log(arr);
return arr;
}

selectionSort([2, 5, 9, 3, 6, 8, 7, 1]);
selectionSort1([2, 5, 9, 3, 6, 8, 7, 1]);

console.log('https://www.cnblogs.com/Unknw/p/6346681.html');

插入排序

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* 插入排序
*/

function insertionSort(arr) {
let len = arr.length,
current,
index;
for (let i = 1; i < len; i++) {
index = i;
current = arr[i];
while (index > 0 && arr[index - 1] > current) {
arr[index] = arr[index - 1];
index--;
}
arr[index] = current;
console.log(arr)
}
console.log(arr);
}

insertionSort([3, 5, 1, 4, 2]);


/*
* 希尔排序是插入排序的一种更高效率的实现。它与插入排序的不同之处在于,它会优先比较距离较远的元素。
* 希尔排序的核心在于间隔序列的设定。既可以提前设定好间隔序列,也可以动态的定义间隔序列。
* 动态定义间隔序列的算法是《算法(第4版》的合著者Robert Sedgewick提出的。
* 在这里,我就使用了这种方法。
*/
function shellSort(arr) {
let len = arr.length,
temp,
gap = 1;
while (gap < len / 3) { //动态定义间隔序列
gap = gap * 3 + 1;
}
for (gap; gap > 0; gap = Math.floor(gap / 3)) {
for (let i = gap; i < len; i++) {
temp = arr[i];
for (let j = i - gap; j >= 0 && arr[j] > temp; j -= gap) {
arr[j + gap] = arr[j];
}
arr[j + gap] = temp;
}
}
return arr;
}