package test1;
import java.util.ArrayList;
import java.util.List;
public class BucketSort {
/**
* 核心思想是將要排序的數列到幾個有序的桶裏,每個桶裏的數據再進行單獨排序,排序完成後,再依次取出每個桶的數據,就是有序數列。
*/
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(5);
list.add(2);
list.add(6);
list.add(9);
list.add(0);
list.add(3);
list.add(4);
System.out.println(list);
list = bucketSort(list,2);
System.out.println(list);
}
public static List<Integer> bucketSort(List<Integer> array,int bucketSize){
//合法性校驗
if(array ==null || array.size()<2||bucketSize<1){
return array;
}
//找出集合中最大值和最小值
int max = array.get(0);
int min = array.get(0);
for(int i=0;i<array.size();i++){
if(array.get(i)>max){
max = array.get(i);
}
if (array.get(i)<min){
min = array.get(i);
}
}
//計算桶的個數 [集合中的min--》集合中的max],表示我們待排序的範圍
int bucketCount = (max-min)/bucketSize+1;
//按照順序建桶,創建一個list,list帶下標是有序的,list中的每一個元素是一個桶
List<List<Integer>> bucketList = new ArrayList<>();
for(int i=0;i<bucketCount;i++){
bucketList.add(new ArrayList<Integer>());
}
//將排序的集合一次性添加到對應的桶中
for (int j=0;j<array.size();j++){
int bucketIndex = (array.get(j)-min)/bucketSize;
bucketList.get(bucketIndex).add(array.get(j));
}
//桶內元素的排序
List<Integer> reusList = new ArrayList<>();
for (int j=0;j<bucketList.size();j++){
List<Integer> everyBucket = bucketList.get(j);
if(everyBucket.size()>0){
if (bucketCount == 1){
bucketSize--;
}
List<Integer> tmp = bucketSort(everyBucket,bucketSize);
for (int i=0;i<tmp.size();i++){
reusList.add(tmp.get(i));
}
}
}
return reusList;
}
}