Bucket Sort in Java

Here you will learn about bucket sort in Java with program example.

Bucket Sort is a sorting algorithm in which elements of given array are distributed into different buckets and then each bucket is sorted individually using some other sorting technique or recursively using bucket sort.

An example is shown in following images.

Bucket Sort in Java
Elements are distributed among different buckets
Bucket Sort in Java
After this, elements are sorted within each bucket

Program for Bucket Sort in Java

Here in this program I have assumed that array elements are positive and less than 10.

package com;

public class BucketSortJava {

	public static void main(String args[]) {
		int i, a[] = {3, 6, 9, 0, 5, 1, 8, 4, 3, 1}, n = 10;
	    
	    System.out.println("Before sorting:\n");
	    for(i = 0; i < n; ++i)
	        System.out.print(a[i] + " ");
	    
	    bucketSort(a, n);
	    
	    System.out.println("\n\nAfter sorting:\n");
	    for(i = 0; i < n; ++i)
	        System.out.print(a[i] + " ");	
	}
 
	static void bucketSort(int a[], int n) {
	    int i, j, k, SIZE = 10;
	    
	    int buckets[] = new int[SIZE];
	    
	    for(i = 0; i < SIZE; ++i)
	        buckets[i] = 0;
	    
	    for(i = 0; i < n; ++i)
	        ++buckets[a[i]];
	        
	    for(i = 0, j = 0; j < SIZE; ++j)
	        for(k = buckets[j]; k > 0; --k)
	            a[i++] = j;
	}
}

Output

Before sorting:

3 6 9 0 5 1 8 4 3 1

After sorting:

0 1 1 3 3 4 5 6 8 9

Leave a Comment

Your email address will not be published. Required fields are marked *