- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingSort.java
More file actions
Latest commit
135 lines (65 loc) · 2.27 KB
/
Copy pathCountingSort.java
File metadata and controls
135 lines (65 loc) · 2.27 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
importjava.util.Scanner;
/** Class CountingSort **/
publicclassCountingSort
{
privatestaticfinalintMAX_RANGE = 1000000;
/** Counting Sort function **/
publicstaticvoidsort( int[] arr )
{
intN = arr.length;
if (N == 0)
return;
/** find max and min values **/
intmax = arr[0], min = arr[0];
for (inti = 1; i < N; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
intrange = max - min + 1;
/** check if range is small enough for count array **/
/** else it might give out of memory exception while allocating memory for array **/
if (range > MAX_RANGE)
{
System.out.println("\nError : Range too large for sort");
return;
}
int[] count = newint[range];
/** make count/frequency array for each element **/
for (inti = 0; i < N; i++)
count[arr[i] - min]++;
/** modify count so that positions in final array is obtained **/
for (inti = 1; i < range; i++)
count[i] += count[i - 1];
/** modify original array **/
intj = 0;
for (inti = 0; i < range; i++)
while (j < count[i])
arr[j++] = i + min;
}
/** Main method **/
publicstaticvoidmain(String[] args)
{
Scannerscan = newScanner( System.in );
System.out.println("Counting Sort Test\n");
intn, i;
/** Accept number of elements **/
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/** Create integer array on n elements **/
intarr[] = newint[ n ];
/** Accept elements **/
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
/** Call method sort **/
sort(arr);
/** Print sorted Array **/
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}