-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorting-algorithm-in-js.js
123 lines (100 loc) · 2.32 KB
/
sorting-algorithm-in-js.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//冒泡排序
const bubbleSort = arr => {
let i, j, len1, len2, tmp;
for (i = 0, len1 = arr.length; i < len1; i++) {
for (j = 0, len2 = len1 - 1 - i; j < len2; j++) {
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
};
//选择排序
const selectionSort = arr => {
let len = arr.length,
indexMin, i, j, tmp;
for (i = 0; i < len - 1; i++) {
indexMin = i;
for (j = i + 1; j < len; j++) {
if (arr[indexMin] > arr[j]) {
indexMin = j;
}
}
if (i !== indexMin) {
tmp = arr[i];
arr[i] = arr[indexMin];
arr[indexMin] = tmp;
}
}
return arr;
};
//插入排序
const insertionSort = arr => {
let len = arr.length,
i, j, tmp;
for (i = 1; i < len; i++) {
j = i;
tmp = arr[i];
while (j > 0 && arr[j - 1] > tmp) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = tmp;
}
return arr;
};
//归并排序
const mergeSort = arr => {
let len = arr.length;
if (len === 1) {
return arr;
}
let mid = Math.floor(len / 2),
left = arr.slice(0, mid),
right = arr.slice(mid);
return merge(mergeSort(left), mergeSort(right));
};
const merge = (left, right) => {
let res = [],
len1 = left.length,
len2 = right.length;
while (len1 > 0 && len2 > 0) {
if (left[0] <= right[0]) {
res.push(left.shift());
len1--;
} else {
res.push(right.shift());
len2--;
}
}
if (len1 > 0) {
res = res.concat(left);
}
if (len2 > 0) {
res = res.concat(right);
}
return res;
};
//快速排序
const quickSort = arr => {
let len = arr.length;
if (len <= 1) {
return arr;
}
let pivotIndex = Math.floor(len / 2),
pivot = arr.splice(pivotIndex, 1)[0],
left = [],
right = [];
len--;
for (let i = 0; i < len; i++) {
if (arr[i] <= pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
};