-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCountingSort.java
50 lines (49 loc) · 990 Bytes
/
CountingSort.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
50
import java.util.*;
class CountingSort
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array->");
int n=sc.nextInt();
int ar[]=new int[n];
System.out.println("Enter the elements of array->");
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
System.out.print("Before Sorting --> ");
for(int i=0;i<n;i++)
{
System.out.print(ar[i]+" ");
}
//Finding Maximum in Array
int t=ar[0];
for(int i=1;i<n;i++)
{
if(t<ar[i])
t=ar[i];
}
int c[]=new int[t+1];
int b[]=new int[n];
for(int j=0;j<n;j++)
{
c[ar[j]]=c[ar[j]]+1;
}
for(int i=1;i<=t;i++)
{
c[i]=c[i]+c[i-1];
}
for(int j=0;j<n;j++)
{
b[c[ar[j]]-1]=ar[j];
c[ar[j]]=c[ar[j]]-1;
}
System.out.println();
System.out.print("After Sorting --> ");
for(int i=0;i<n;i++)
{
System.out.print(b[i]+" ");
}
}
}