最近笔试经常看到的一道题,对大数据量的长数字进行排序,要求高效,如IP地址。方法是使用位图排序,也叫计数排序,原理非常简单,自己写了一个 Java 的实现,记录一下。
题目描述:对一个最多可以是1千万个数字的集合的数组排序,最大数字1千万,数字不重复。(若数字重复,可将 byte 换成 int,进行累加)
优缺点:优点是快速、占用资源少,缺点是只能对整数使用。
算法思路:
1. 创建一个 bytes[n], n = 1千万;
2. 遍历数组,将数组中的数字所对应的位标记为1;
3. 遍历 bytes[n],将标记为1的索引(即数组中的数字)输出。
Java 实现:
public class BitmapSort {
static void bitmapSort(int[] arr) {
int n = 100000000;
byte[] bytes = new byte[n];
for (int num : arr) {
bytes[num]= 1;
}
for (int i = 0; i <bytes.length; i++) {
if (bytes[i] == 1) {
System.out.println(i);
}
}
}
public staticvoid main(String[]args) {
int[] arr = { 90, 48,907, 3246, 554, 34, 53, 2, 121 };
bitmapSort(arr);
}
}
输出:2
34
48
53
90
121
554
907
3246