-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathCountSort.java
More file actions
56 lines (48 loc) · 1.35 KB
/
Copy pathCountSort.java
File metadata and controls
56 lines (48 loc) · 1.35 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
/**
* Created by dheeraj on 12/18/14.
*/
public class CountSort {
int[] array;
int arrayLength;
int maxValue;
private int findMaxValue(int[] arr){
int max = arr[0];
for(int k =1;k<arr.length;k++){
if(max < arr[k]){
max = arr[k];
}
}
return max;
}
public CountSort(int[] array){
this.array = array;
this.arrayLength = array.length;
this.maxValue = findMaxValue(array)+1;
}
public int[] sort(){
int[] hashArray = new int[maxValue];
int[] resultArray = new int[arrayLength];
for(int a =0;a<maxValue;a++){
hashArray[a]=0;
}
for(int a=0;a<arrayLength;a++){
hashArray[array[a]] = hashArray[array[a]] + 1;
}
for(int a=1;a<maxValue;a++){
hashArray[a] = hashArray[a] + hashArray[a-1];
}
for(int a = arrayLength-1;a>=0;a--){
hashArray[array[a]] = hashArray[array[a]] -1;
resultArray[hashArray[array[a]]] = array[a];
}
return resultArray;
}
public static void main(String[] args){
int[] arr = {1,2,3,1,3,2,5,6};
CountSort countSort = new CountSort(arr);
arr = countSort.sort();
for(int a =0;a<arr.length;a++){
System.out.println(arr[a]+" ");
}
}
}