Skip to content

Commit 58d5782

Browse files
committed
feat: complete insertSectionSort
1 parent 2f17c1f commit 58d5782

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

code/sort/insertSort.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 插入排序
3+
* 理解:
4+
* 就像我们打牌一样,从左->右,依次为 A 2 3 4 5 ...从小到大的顺序(当然这是我们排好牌的情况下)。
5+
* 码牌的过程和插入排序一样:把最右边的牌依次向左边每一张牌比较,放在合适的位置,当右边的牌处理完的情况下。整个牌也就处理好了。
6+
*
7+
* 当然这里有一个点:默认情况下你第一张是处理正常的不做处理
8+
*/
9+
10+
11+
12+
function insertSort(arr: number[]) {
13+
for (let index = 1; index < arr.length; index++) {
14+
let j = index;
15+
while (j > 0 && arr[j - 1] > arr[j]) {
16+
let tmp = arr[j];
17+
arr[j] = arr[j-1]
18+
arr[j-1] = tmp;
19+
j--
20+
}
21+
}
22+
return arr
23+
}
24+
25+
26+
function insertSort2(arr: number[]) {
27+
let tmp;
28+
for (let index = 1; index < arr.length; index++) {
29+
let j = index;
30+
tmp = arr[index]
31+
// 如果存在左边值大于右边且j > 0的情况
32+
while (j > 0 && arr[j - 1] > tmp) {
33+
arr[j] = arr[j-1] // 把左边值与相邻的右边交换
34+
j--
35+
}
36+
arr[j] = tmp // 执行完之后此时j,1. 与index完全相同 2.发生交换后,左侧交换的位置
37+
}
38+
return arr
39+
}
40+
41+
const insertSortTestArr = [5, 4, 3, 2, 1];
42+
43+
console.time("insertSort2");
44+
console.log(insertSort2(insertSortTestArr));
45+
console.timeEnd("insertSort2");

code/sort/selectionSort.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
* 思路为找到数组中最小的数值,放到最前面。然后依次处理整个数组
66
* 时间 O(n2)
77
* 空间 O(1)
8+
*
9+
* 相比于冒泡排序:效率高在进行位置交换时,次数少于bubbleSort
810
*/
911

1012

1113
const a = [5, 4, 3, 2, 1];
1214

1315

14-
const b = [5, 4, 3, 2, 1];
15-
16-
16+
const e = [5, 4, 3, 2, 1];
1717

1818

1919

@@ -37,7 +37,7 @@ function selectionSort(arr: number[]) {
3737

3838

3939
console.time("selectionSort");
40-
console.log(selectionSort(b));
40+
console.log(selectionSort(e));
4141
console.timeEnd("selectionSort"); // 2.4ms
4242

4343

0 commit comments

Comments
 (0)