Skip to content

Instantly share code, notes, and snippets.

@maycuatroi1
Created October 26, 2025 22:51
Show Gist options
  • Select an option

  • Save maycuatroi1/fcf6d905ecca03c493eac3bd582acb80 to your computer and use it in GitHub Desktop.

Select an option

Save maycuatroi1/fcf6d905ecca03c493eac3bd582acb80 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collections;
public class BucketSort {
public static void bucketSort(int[] arr) {
if (arr.length == 0) {
return;
}
// Find maximum and minimum values
int max = arr[0];
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// Create buckets
int bucketCount = arr.length;
ArrayList<ArrayList<Integer>> buckets = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
buckets.add(new ArrayList<>());
}
// Distribute elements into buckets
int range = max - min + 1;
for (int i = 0; i < arr.length; i++) {
int bucketIndex = (int) ((long) (arr[i] - min) * bucketCount / range);
if (bucketIndex >= bucketCount) {
bucketIndex = bucketCount - 1;
}
buckets.get(bucketIndex).add(arr[i]);
}
// Sort individual buckets and concatenate
int index = 0;
for (int i = 0; i < bucketCount; i++) {
Collections.sort(buckets.get(i));
for (int j = 0; j < buckets.get(i).size(); j++) {
arr[index++] = buckets.get(i).get(j);
}
}
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original array:");
printArray(arr);
bucketSort(arr);
System.out.println("Sorted array:");
printArray(arr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment