File tree 2 files changed +79
-0
lines changed
2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 计数排序
3
+ * 一般适用于数值的范围不大的正整数(也可包括0)数组
4
+ * (如果需要考虑负整数,可考虑将数组分为两个数组,一个正整数数组、一个负整数数组,分别处理,再合并)
5
+ * 1、第一步找到这个数组中的最大值,用于决定计数数组count的长度
6
+ * 2、遍历数组,将出现的数字arr[i]作为count数组的下标,每出现一次这个数字,则count[arr[i]]++,最后count数组将记录下原数组中每个数字出现的次数
7
+ * 3、遍历count数组,某个数字出现几次,就向结果数组中push几个该数字
8
+ */
9
+
10
+ const countSort = ( arr ) => {
11
+ let len = arr . length ;
12
+ let max = arr [ 0 ] ;
13
+ // 找到数组中的最大值
14
+ for ( let i = 0 ; i < len ; i ++ ) {
15
+ if ( arr [ i ] > max ) {
16
+ max = arr [ i ] ;
17
+ }
18
+ }
19
+
20
+ const count = new Array ( max + 1 ) . fill ( 0 ) ;
21
+
22
+ // 计数
23
+ for ( let i = 0 ; i < len ; i ++ ) {
24
+ count [ arr [ i ] ] ++ ;
25
+ }
26
+
27
+ len = count . length ;
28
+ const result = [ ] ;
29
+ for ( let i = 0 ; i < len ; i ++ ) {
30
+ while ( count [ i ] > 0 ) {
31
+ result . push ( i ) ;
32
+ count [ i ] -- ;
33
+ }
34
+ }
35
+
36
+ return result ;
37
+ } ;
38
+
39
+ // test case:
40
+ const arr = Array . from ( { length : 100 } ) . map ( ( ) =>
41
+ Math . floor ( Math . random ( ) * 100 )
42
+ ) ;
43
+
44
+ console . log ( countSort ( arr ) ) ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 计数排序
3
+ * 一般适用于数值的范围不大的正整数(也可包括0)数组
4
+ * (如果需要考虑负整数,可考虑将数组分为两个数组,一个正整数数组、一个负整数数组,分别处理,再合并)
5
+ * 2、遍历数组,将出现的数字arr[i]作为count数组的下标,每出现一次这个数字,则count[arr[i]]++,最后count数组将记录下原数组中每个数字出现的次数
6
+ * 3、遍历count数组,某个数字出现几次,就向结果数组中push几个该数字
7
+ */
8
+
9
+ const countSort = ( arr ) => {
10
+ let len = arr . length ;
11
+ const count = [ ] ;
12
+
13
+ // 计数
14
+ for ( let i = 0 ; i < len ; i ++ ) {
15
+ count [ arr [ i ] ] = ( count [ arr [ i ] ] || 0 ) + 1 ;
16
+ }
17
+
18
+ len = count . length ;
19
+ const result = [ ] ;
20
+ for ( let i = 0 ; i < len ; i ++ ) {
21
+ while ( count [ i ] ) {
22
+ result . push ( i ) ;
23
+ count [ i ] -- ;
24
+ }
25
+ }
26
+
27
+ return result ;
28
+ } ;
29
+
30
+ // test case:
31
+ const arr = Array . from ( { length : 300 } ) . map ( ( ) =>
32
+ Math . floor ( Math . random ( ) * 100 )
33
+ ) ;
34
+
35
+ console . log ( countSort ( arr ) ) ;
You can’t perform that action at this time.
0 commit comments