Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class CountSort{
- public static void main(String args[]){
- System.out.println("Enter the size of array");
- Scanner sc = new Scanner(System.in);
- int len = sc.nextInt();
- int a[] = new int[len];
- int largest = 0;
- System.out.println("Enter the array");
- for(int x = 0; x<len; x++){
- a[x] = sc.nextInt();
- if(a[x] > largest){
- largest = a[x];
- }
- }
- int b[] = new int[largest+1];
- Arrays.fill(b, 0);
- for(int x = 0; x<len; x++){
- b[a[x]] += 1;
- }
- System.out.print("\nFrequencies of the array\n");
- System.out.println(Arrays.toString(b));
- int c[] = new int[len];
- /*
- Here starts the different approach, ie fill the new array c with the number of times a number appears
- in the frequency array b. Example is 0 appears 2 times in b then put 2 0s in c and move on.
- */
- int index = 0;
- int value;
- for(int x = 0; x<largest+1; x++){
- value = b[x];
- if(value == 0){
- continue;
- }
- else{
- while(value > 0){
- c[index] = x;
- index += 1;
- value -= 1;
- }
- }
- }
- System.out.print("\nSorted array\n");
- System.out.println(Arrays.toString(c));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment