w3resource
Java Programming Exercies

Java Exercises: Bucket Sort Algorithm

Java Sorting Algorithm: Exercise-19 with Solution

Write a Java program to sort an array of given integers using Bucket Sort Algorithm.

Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a distribution sort, a generalization of pigeonhole sort, and is a cousin of radix sort in the most-to-least significant digit flavor.

Sample Solution:

Java Code:

import java.util.Arrays;
public class BucketSort 
{
    static int[] sort(int[] nums, int max_value) 
    {
        // Bucket Sort
        int[] Bucket = new int[max_value + 1];
        int[] sorted_nums = new int[nums.length];
         for (int i = 0; i < nums.length; i++)
          Bucket[nums[i]]++;
          int outPos = 0;
         for (int i = 0; i < Bucket.length; i++)
              for (int j = 0; j < Bucket[i]; j++)
                  sorted_nums[outPos++] = i;
          return sorted_nums;
      }
 
    static int max_value(int[] nums) 
    {
        int max_value = 0;
        for (int i = 0; i < nums.length; i++)
            if (nums[i] > max_value)
                max_value = nums[i];
        return max_value;
    } 
// Method to test above
    public static void main(String args[])
    {
        int nums[] = {7, 3, 2, 1, 0, 45};
       int max_value = max_value(nums);
        System.out.println("Original Array:");
        System.out.println(Arrays.toString(nums));
        nums = sort(nums, max_value);
        System.out.println("Sorted Array:");
        System.out.println(Arrays.toString(nums));
        }        
}

Sample Output:

Original Array:
[7, 3, 2, 1, 0, 45]
Sorted Array:
[0, 1, 2, 3, 7, 45]

Flowchart:

Sort an array of given integers using Bucket Sort Algorithm

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to sort an array of given non-negative integers using Stooge Sort Algorithm.
Next: Java Sorting Algorithm Exercises

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming