com.rao.sort Package;
Import Classes in java.util. * ;
/ * *
* @author Srao
* @className BucketSort
* @date 2019/12/10 17:42
* @package com.rao.sort
* @Description bucket sort
* /
public class bucketSort {
/ * *
* bucket sort
* @param ARR
* @return
* /
public static Double [] bucketSort ( Double [] ARR) {
// 1. calculate the maximum and minimum values, determined both difference
Double min ARR = [ 0 ];
Double max = ARR [ 0 ];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]){
max = arr[i];
}
if (arr[i] < min){
min = arr[i];
}
}
double d = max - min;
//2.初始化桶
int bucketNum = arr.length;
List<LinkedList<Double>> bucketList = new ArrayList<>(bucketNum);
for (int i = 0; I <bucketNum; I ++ ) {
bucketList.add ( new new the LinkedList <> ());
}
// 3. traverse the elements in the array, all the elements which are placed in the corresponding bucket
for ( int I = 0 ; I < arr.length; I ++ ) {
// compute the current element which should be placed inside the tub
int NUM = ( int ) ((ARR [I] - min) / (D / (bucketNum - . 1 )));
bucketList. GET (NUM ) .add (ARR [I]);
}
// 4. for each of the elements inside the barrel sort
for ( int I = 0 ; I <bucketNum; I ++ ) {
the Collections.sort (bucketList.get(i));
}
//5.输出全部元素
int k = 0;
for(LinkedList<Double> doubles : bucketList){
for (Double aDouble : doubles) {
arr[k] = aDouble;
k++;
}
}
return arr;
}
public static void main(String[] args) {
double[] arr = new double[]{4.12, 6.421, 0.0023, 3.0, 2.123, 8.122, 4.12, 10.09};
System.out.println(Arrays.toString(arr));
arr = bucketSort(arr);
System.out.println(Arrays.toString(arr));
}
}
Bucket sort can be seen as an improvement on counting sort, counting sort for a range of values in an array of integers can be sorted, but for an array of decimal places have no way to count, this time we should use the bucket sort.
Bucket sort is to divide the array into a different number of intervals, and then the number in each bucket sorting, sorting algorithm used at this time is generally merge sort or quick sort and then returns the number of all the tub to the original array.