借鉴:借鉴跳转,上面都有详细的描述以及动图的实现。
桶排序(Bucket Sort)
桶排序 (Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶子里。每个桶子再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。–百度百科
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
//桶排序
public class BucketSort {
public static void main(String[] args) {
int[] arr = {1,5,21,6,43,52,2,0,6,11,2};
Object[] objects = bucketSort(arr);
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
public static Object[] bucketSort(int[] arr) {
if (arr == null || arr.length < 2) {
return null;
}
int max = arr[0], min = arr[0], temp, cur,size,count,len=arr.length;
//获取最大最小值
for (int i = 0; i < arr.length; i++) {
cur = arr[i];
if (max < cur) {
max = cur;
}
if (min > cur) {
min = cur;
}
}
//初始化桶
count =(max-min)/len +1;
List<LinkedList<Integer>> outBuckets = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
outBuckets.add(new LinkedList<Integer>());
}
//把数装进对应的小桶中
for (int i = 0; i < len; i++) {
int index = (arr[i]-min)/len;
outBuckets.get(index).add(arr[i]);
}
LinkedList<Integer> resList = new LinkedList<>();
//对小桶中的数据进行快速排序
for (int i = 0; i < outBuckets.size(); i++) {
quickSort(outBuckets.get(i),0,outBuckets.get(i).size()-1);
//将排好序的数据取出来
resList.addAll(outBuckets.get(i));
}
return resList.toArray();
}
private static int partition(LinkedList<Integer> arr, int left, int right) {
int temp = arr.get(left);
while (left < right) {
while (temp <= arr.get(right) && left < right) {
right--;
}
if (left < right) {
arr.set(left,arr.get(right));
left++;
}
while (temp >= arr.get(left) && left < right) {
left++;
}
if (left < right) {
arr.set(right,arr.get(left));
right--;
}
}
arr.set(left, temp);
return left;
}
private static void quickSort(LinkedList<Integer> arr, int left, int right) {
if (left >= right || arr == null || arr.size() <= 1) {
return;
}
int mid = partition(arr, left, right);
quickSort(arr, left, mid);
quickSort(arr, mid + 1, right);
}
}