位排序

 1 /**
 2  * 位图排序
 3  */
 4 import java.util.Arrays;
 5 
 6 public class Test {
 7     public static void main(String[] args){
 8         int[] arr = new int[]{ 3, 6, 7, 13, 1, 0, 4, 2, 9, 8, 15, 11 };
 9         System.out.println(Arrays.toString(arr));
10         System.out.println("================");
11         BitSort.bitSort(arr, 15);
12         System.out.println(Arrays.toString(arr));
13     }
14 }
15 
16 class BitSort{
17     /**
18      *
19      * @param arr 待排序树组
20      * @param maxValue 数组中最大值,用来确定位图数组大小
21      */
22     public static void bitSort(int[] arr, int maxValue){
23         //位图数组大小为: maxValue/8-1,因为位图从0开始
24         byte[] bitlist = new byte[maxValue / 8 + 1];
25         for(int i = 0; i < arr.length; i++){
26             //确定arr[i]所放的bitlist位置
27             int index = arr[i] / 8;
28             //arr[i]值为多少就在位图中左移多少, 通过或(|)操作来记录每个数据
29             bitlist[index] = (byte)(bitlist[index] | (0x01 << (arr[i] % 8)));
30         }
31 
32         int k = 0;
33         for(int i = 0; i < bitlist.length; i++){
34             //遍历bitlist的每一个位
35             for(int j = 0; j < 8; j++){
36                 if((0x01 & (bitlist[i] >> j)) == 1){
37                     arr[k++] = i * 8 + j;
38                 }
39             }
40         }
41     }
42 }
View Code
原文地址:https://www.cnblogs.com/Hr666/p/10403438.html