Count sort in java


Contents of page >
  • Full Program/SourceCode/Example to sort array using count sort in java>
  • Output of count sort program >


Also read : Radix sort




Full Program/SourceCode/Example to sort array using count sort in java>
/**
*  write a program to sort array using Count Sort in java.
*/
public class CountSortAlgorithmExample {
   /**
   * Declare initialize array which has to be sorted using Count sort in java
   */
   private int[] arr = { 12, 3, 8, 9, 1, 14, 6, 7, 5, 89 };
   /**
   * This method Sort Array using Count Sort in java
   */
  
   public void countSort() {
          int n = arr.length;
          // Create a array to store count of all the elements of array
          int newArr[] = new int[100];
         
          for (int i = 0; i < 100; ++i)
                 newArr[i] = 0; //Initialize count array as 0
          // store count of each character
          for (int i = 0; i < n; ++i)
                 ++newArr[arr[i]];
          // Change newArr[i] so that newArr[i] now contains actual
          // position of this int in sortedArray array
          for (int i = 1; i <= 99; ++i)
                 newArr[i] += newArr[i - 1];
         
          // Create sortedArray - to store sorted arr
          int sortedArray[] = new int[n];
         
          //Now, populate the sortedArray
          for (int i = 0; i < n; ++i) {
                 sortedArray[newArr[arr[i]] - 1] = arr[i];
                 --newArr[arr[i]];
          }
         
          // Now,
          // Copy elements of sortedArray array to arr
          // So, arr will be the sorted array now.
          for (int i = 0; i < n; ++i)
                 arr[i] = sortedArray[i];
   }
  
   /**
   * This method Display Array
   */
   public void display() {
          for (int i = 0; i < arr.length; i++) {
                 System.out.print(arr[i] + " ");
          }
   }
   public static void main(String[] args) {
          CountSortAlgorithmExample countSort = new CountSortAlgorithmExample();
          System.out.print("Display Array elements before Count sorting : ");
          countSort.display(); // display unsorted array
          countSort.countSort(); // count sort the array
          System.out.print("\nDisplay Array elements after Count sorting  : ");
          countSort.display(); // display sorted array
   }
}
/*output
Display Array elements before Count sorting : 12 3 8 9 1 14 6 7 5
Display Array elements after Count sorting  : 1 3 5 6 7 8 9 12 14
*/


Output of count sort program >

Summary >
So in this data structure tutorial we learned Count sort in java.

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>
eEdit
Must read for you :