import java.util.Arrays;
public class BucketSort {
public static void bucketSort(int[] arr, int maxBucketNum){
if (arr==null || arr.length<2 || maxBucketNum<1){
return;
}
int max = 0;
int min = 0;
for (int i: arr){
if (i>max){
max=i;
}
if (i<min){
min=i;
}
}
int range = (max-min)/maxBucketNum+1;
int[][] buckets = new int[maxBucketNum][];
int bucketIndex;
for (int i: arr){
bucketIndex = (i-min)/range;
buckets[bucketIndex] = appendItem(buckets[bucketIndex], i);
}
for (int i = 0;i<buckets.length;i++){
if (buckets[i]==null||buckets[i].length<2){
continue;
}
quickSort(buckets[i], 0, buckets[i].length-1);
}
int k =0;
for (int[] b:buckets){
if (b != null){
for (int j: b){
arr[k] = j;
k++;
}
}
}
}
private static int[] appendItem(int[] bucket, int val){
int[] arr;
if (bucket == null||bucket.length==0){
arr = new int[]{val};
}else {
arr = Arrays.copyOf(bucket, bucket.length+1);
arr[bucket.length] = val;
}
return arr;
}
private static void quickSort(int[] arr, int left, int right){
if (left<right){
int pointer = position(arr, left, right);
quickSort(arr, left, pointer-1);
quickSort(arr, pointer+1, right);
}
}
private static int position(int[] arr, int left, int right){
int pointer = left;
int val = arr[right];
for (int i=left;i<right;i++){
if (arr[i]<val){
int temp = arr[i];
arr[i] = arr[pointer];
arr[pointer] = temp;
pointer++;
}
}
arr[right] = arr[pointer];
arr[pointer] = val;
return pointer;
}
public static void main(String[] args) {
int[] arr = {52, 12, 46, 72, 4, 19, 45, 75, 7, 23, 64, 32, 28, 62, 54};
bucketSort(arr, 4);
for (int i:arr){
System.out.print(i+" ");
}
}
}
Java桶排序
于 2023-08-31 15:51:40 首次发布