Bucket sort in java



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


Also read : Insertion Sort





Full Program/SourceCode/Example to sort array using bucket sort in java>
/**
*  write a program to sort array using Bucket Sort in java.
*/
public class BucketSortAlgorithmExample {
   /**
   * Declare initialize array which has to be sorted using Bucket sort in java
   */
   private static int[] arr = { 12, 3, 8, 9, 1, 14, 6, 7, 5, 89 };
  
   /**
   * This method Sort Array using Bucket Sort in java
   */
   static void bucketSort(int maxValue) {
          int[] bucketArray = new int[maxValue + 1];
          for (int i = 0; i < arr.length; i++)
                 bucketArray[arr[i]]++;
          // Create sortedArray - to store sorted arr
          int[] sortedArray = new int[arr.length];
          int x = 0;
          for (int i = 0; i < bucketArray.length; i++)
                 for (int j = 0; j < bucketArray[i]; j++)
                       sortedArray[x++] = i;
          // Now,
          // Copy elements of sortedArray array to arr
          // So, arr will be the sorted array now.
          arr = sortedArray;
   }
   /**
    * Method to find the maximum value in the array
    */
   static int maxValue() {
          int maxValue = 0;
          for (int i = 0; i < arr.length; i++)
                 if (arr[i] > maxValue){
                       maxValue = arr[i];
                 }
          return maxValue;
   }
  
   /**
   * This method Display Array
   */
   public static void display() {
          for (int i = 0; i < arr.length; i++) {
                 System.out.print(arr[i] + " ");
          }
   }
   public static void main(String[] args) {
          System.out.print("Display Array elements before Bucket sorting : ");
          BucketSortAlgorithmExample.display(); // display unsorted array
          BucketSortAlgorithmExample.bucketSort(maxValue()); // bucket sort the array
          System.out.print("\nDisplay Array elements after Bucket sorting  : ");
          BucketSortAlgorithmExample.display(); // display sorted array
   }
}
/*output
Display Array elements before Bucket sorting : 12 3 8 9 1 14 6 7 5
Display Array elements after Bucket sorting  : 1 3 5 6 7 8 9 12 14
*/



Output of Bucket sort program >
Display Array elements before Bucket sorting : 12 3 8 9 1 14 6 7 5
Display Array elements after Bucket sorting  : 1 3 5 6 7 8 9 12 14

Summary >
So in this data structure tutorial we learned Bucket sort in jav.

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.




eEdit
Must read for you :