本篇博客是今天笔者写的最后一篇排序算法的博客了。桶排序(bucket sort)假设输入数据服从均匀分布,平均情况下其时间代价为O(n)。计数排序假设数据都属于一个小区间的整数,而桶排序则假设数据均匀、独立分布在[0,1)上。
桶排序将区间[0,1)划分为n各大小相同的子区间,称之为桶,然后将数组中的所有元素都放在对应的桶中。为了得到排序结果,先对桶中的元素进行排序,然后依次遍历每个桶把桶中的元素依次列出来即可。将元素放置对应的桶的过程是数组元素乘上桶的个数并向下取整。为了灵活起见,桶采用链表实现。
示例代码如下:
package org.vimist.pro.Algorithm.Sort;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* An demonstration of {@code BucketSort}.
*
* @author Mr.K
*/
public class BucketSort {
public static void main(String[] args) {
int N = 10;
float[] arr = new float[N], copies = new float[N];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextFloat();
}
System.arraycopy(arr, 0, copies, 0, N);
System.out.println("待排序数组: " + Arrays.toString(arr));
Bucket_Sort(arr);
System.out.println("已排序数组: " + Arrays.toString(arr));
Arrays.sort(copies);
System.out.println("参考 数组: " + Arrays.toString(copies));
}
/**
* Accepts an array and sorts the specified array using {@code BucketSort}.
* In the example, each element locates in the range from 0(inclusive) to 1
* (exclusive) and random uniformly distributes. The process compromise 4
* steps, which are:
* <ul>
* <li>The first step is to initialize an array, each element is a list, and
* initialize each list, which can be called a <em>Bucket</em></li>
* <li>The second step is to place each element in the specified array
* into the rightful bucket.</li>
* <li>The third step is to sort each list in the newly-established array.
* </li>
* <li>The last step is to reassign value from each non-empty list to the
* specified array by order.</li>
* </ul>
* {@code BucketSort} is a liner sort. In this sort, there exists some assumptions
* like {@link CountingSort#Counting_Sort(int[])}.
*
* @param arr specified array to be sorted
*/
private static void Bucket_Sort(@NotNull float[] arr) {
int index = 0;
LinkedList<Float>[] lists = new LinkedList[10];
for (int i = 0; i < lists.length; i++) {
lists[i] = new LinkedList<>();
}
for (int i = 0; i < arr.length; i++) {
lists[(int) (arr[i] / 0.1)].add(arr[i]);
}
for (int i = 0; i < lists.length; i++) {
Collections.sort(lists[i]);
}
for (int i = 0; i < lists.length; i++) {
if (!lists[i].isEmpty()) {
Iterator iterator = lists[i].iterator();
while (iterator.hasNext()) {
arr[index++] = (float) iterator.next();
}
}
}
}
}
运行结果如下:
待排序数组: [0.1410836, 0.64014935, 0.68507814, 0.488932, 0.8883444, 0.63293314, 0.4323581, 0.098573446, 0.21807796, 0.36170465]
已排序数组: [0.098573446, 0.1410836, 0.21807796, 0.36170465, 0.4323581, 0.488932, 0.63293314, 0.64014935, 0.68507814, 0.8883444]
参考 数组: [0.098573446, 0.1410836, 0.21807796, 0.36170465, 0.4323581, 0.488932, 0.63293314, 0.64014935, 0.68507814, 0.8883444]