File tree 1 file changed +57
-0
lines changed
1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ void print (int [], int );
4
+ void counting_sort (int [], int );
5
+ int find_max (int [], int );
6
+
7
+ int main ()
8
+ {
9
+ int array[] = {3 , 5 , 1 , 3 };
10
+ int array_size = sizeof (array) / sizeof (*array);
11
+
12
+ counting_sort (array, array_size);
13
+
14
+ return 0 ;
15
+ }
16
+
17
+ void print (int A[], int n)
18
+ {
19
+ for (int i = 0 ; i < n; i++)
20
+ std::cout << A[i] << " " ;
21
+ std::cout << std::endl;
22
+ }
23
+
24
+ void counting_sort (int A[], int n)
25
+ {
26
+ int max_num = find_max (A, n);
27
+ int count_array[max_num + 1 ] = {0 };
28
+
29
+ for (int i = 0 ; i < n; i++)
30
+ count_array[A[i]]++;
31
+
32
+ int old_index = 0 ;
33
+ for (int j = 0 ; j < max_num + 1 ; j++)
34
+ {
35
+ if (count_array[j] > 0 )
36
+ {
37
+ while (count_array[j])
38
+ {
39
+ A[old_index] = j;
40
+ old_index++;
41
+ count_array[j]--;
42
+ }
43
+ }
44
+ }
45
+ print (A, n);
46
+ }
47
+
48
+ int find_max (int A[], int n)
49
+ {
50
+ int max_num = 0 ;
51
+ for (int i = 0 ; i < n; i++)
52
+ {
53
+ if (A[i] > max_num)
54
+ max_num = A[i];
55
+ }
56
+ return max_num;
57
+ }
You can’t perform that action at this time.
0 commit comments