Count sort 10th Section count sort Exercises
For an int array, write a counting sort algorithm that sorts the array elements.
Given an int array a and the size of the array n, return the sorted array.
Test examples:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
Java (javac 1.7)Code Auto-Complete1
Import Java. util. *;
2
3
Public class Countingsort {
4
Public int Countingsort (intAintn) {
5
Countingsort (A);
6
return A;
7
}
8
9
Public void Countingsort (intarr{
10
int Temparr = New int [arr. length]; //Temporary array
11
int Timesarr; //Count the number of occurrences of each element and put it in the corresponding bucket
12
int range; //Statistic the range of this group to get how many buckets are needed
13
int Max = arr [0];
14
int min = arr [0];
15
for (intaarr) {
16
if (a>max)
17
Max = a;
18
if (a<min)
19
min = a;
20
}
21st
Range = Max - min + 1; //Derive the extremum difference, in order to reduce the length of the temporary array (counting the number of occurrences of each element)
22
Timesarr = New int [range];
23
24
for (inti=0i<arr.) length I ++) {
25
Timesarr [arr[i-min]+ +;
26
}
27
for (inti=1i<Timesarr. length I ++) {//Get the overall order on the size of all elements
28
Timesarr [i+ =Timesarr[i-1];
29
}
30
for (inti=0i<arr.) length I ++) {//to correspond the position order of elements in arr to a temporary array
31
int position = Timesarr [arr[i-min]; //Get arr[i] The position of this element on the whole
32
Temparr [--position=arr[i]; //Based on the position above, put the element into a temporary array
33
Timesarr [arr[i-min]-;
34
}
35
for (inti=0i<arr.) length I ++) {
36
arr [i=Temparr[i];
37
}
38
}
39
}
Your code is saved
The answer is right: Congratulations! The program you submitted passed all of the test cases
Algorithm-java code Implementation count sort