File tree 4 files changed +85
-0
lines changed
labuladong/lesson-basic/Sort
4 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ function sort ( nums ) {
2
+ const n = nums . length ;
3
+ let sortedIndex = 0 ;
4
+ while ( sortedIndex < n ) {
5
+ // 寻找 nums[sortedIndex..] 中的最小值
6
+ // 同时将这个最小值逐步移动到 nums[sortedIndex] 的位置
7
+ for ( let i = n - 1 ; i > sortedIndex ; i -- ) {
8
+ if ( nums [ i ] < nums [ i - 1 ] ) {
9
+ // swap(nums[i], nums[i - 1])
10
+ let tmp = nums [ i ] ;
11
+ nums [ i ] = nums [ i - 1 ] ;
12
+ nums [ i - 1 ] = tmp ;
13
+ }
14
+ }
15
+ sortedIndex ++ ;
16
+ }
17
+ console . log ( nums )
18
+ }
19
+ // 进一步优化,数组有序时提前终止算法
20
+ function sort1 ( nums ) {
21
+ const n = nums . length ;
22
+ let sortedIndex = 0 ;
23
+ while ( sortedIndex < n ) {
24
+ // 加一个布尔变量,记录是否进行过交换操作
25
+ let swapped = false ;
26
+ for ( let i = n - 1 ; i > sortedIndex ; i -- ) {
27
+ if ( nums [ i ] < nums [ i - 1 ] ) {
28
+ // swap(nums[i], nums[i - 1])
29
+ let tmp = nums [ i ] ;
30
+ nums [ i ] = nums [ i - 1 ] ;
31
+ nums [ i - 1 ] = tmp ;
32
+ swapped = true ;
33
+ console . log ( 1 )
34
+ }
35
+
36
+ }
37
+ // 如果一次交换操作都没有进行,说明数组已经有序,可以提前终止算法
38
+ if ( ! swapped ) {
39
+ break ;
40
+ }
41
+ sortedIndex ++ ;
42
+ }
43
+ }
44
+ sort1 ( [ 1 , 6 , 3 , 6 , 7 ] )
Original file line number Diff line number Diff line change
1
+ // 对选择排序进一步优化,想左侧有序数组中插入元素
2
+ // 这个算法有另一个名字,叫做插入排序
3
+ function sort ( nums ) {
4
+ const n = nums . length ;
5
+ // 维护 [0, sortedIndex) 是有序数组
6
+ let sortedIndex = 0 ;
7
+ while ( sortedIndex < n ) {
8
+ // 将 nums[sortedIndex] 插入到有序数组 [0, sortedIndex) 中
9
+ for ( let i = sortedIndex ; i > 0 ; i -- ) {
10
+ if ( nums [ i ] < nums [ i - 1 ] ) {
11
+ let tmp = nums [ i ] ;
12
+ nums [ i ] = nums [ i - 1 ] ;
13
+ nums [ i - 1 ] = tmp ;
14
+ } else {
15
+ break ;
16
+ }
17
+ }
18
+ sortedIndex ++ ;
19
+ }
20
+ }
Original file line number Diff line number Diff line change
1
+ //选择排序
2
+ function sort ( nums ) {
3
+ // 你的代码,将 nums 中的元素从小到大排序
4
+ const n = nums . length ;
5
+ let sortIndex = 0 ;
6
+ while ( sortIndex < n ) {
7
+ let minIndex = sortIndex ;
8
+ for ( let i = sortIndex + 1 ; i < n ; i ++ ) {
9
+ if ( nums [ minIndex ] > nums [ i ] ) {
10
+ minIndex = i ;
11
+ }
12
+ }
13
+ [ nums [ minIndex ] , nums [ sortIndex ] ] = [ nums [ sortIndex ] , nums [ minIndex ] ]
14
+ sortIndex ++ ;
15
+ //console.log(sortIndex)
16
+ }
17
+ console . log ( nums )
18
+ }
19
+
20
+ sort ( [ 1 , 2 , 4 , 5 , 6 , 8 , 3 , 1 ] )
Original file line number Diff line number Diff line change
1
+ # 排序算法的关键指标
You can’t perform that action at this time.
0 commit comments