-
Notifications
You must be signed in to change notification settings - Fork 39
/
countsort.java
49 lines (45 loc) · 1.3 KB
/
countsort.java
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
package com.company;
import java.util.Scanner;
public class tc_count_sort {
public static void countSort(int[] arr, int min, int max) {
int range=max-min+1;
int [] farr= new int[range];
for(int i=0;i<arr.length;i++){
int idx=arr[i]-min;
farr[idx]++;
}
for(int i= 1;i<farr.length;i++){
farr[i]=farr[i]+farr[i-1];
}
int [] ans=new int[arr.length];
for(int i=arr.length-1;i>=0;i--){
int val=arr[i];
int pos=farr[val-min];
int idx=pos-1;
ans[idx]=val;
pos--;
}
for(int i=0;i<arr.length;i++){
arr[i]=ans[i];
}
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
max = Math.max(max, arr[i]);
min = Math.min(min, arr[i]);
}
countSort(arr,min,max);
print(arr);
}
}