PHP实现 bitmap 位图排序 求交集
2014年12月16日 17:15:09
初始化一串全为0的二进制;
现有一串无序的整数数组;
如果整数x在这个整数数组当中,就将二进制串的第x位置为1;
然后顺序读取这个二进制串,并将为1的位转换成整数,顺序存放到新的集合中,就是排好序的了
排序代码:
1 function sort() 2 { 3 // var_dump(PHP_INT_MAX, PHP_INT_SIZE); 4 // int 9223372036854775807 5 // int 8 6 $bitmap = array_fill(0, 50, 0); //申请一个整形数组, 50个元素, 初始化为整数0 7 $int_bit_size = PHP_INT_SIZE * 8; //$bitmap中每个整形的二进制位数 (本例中int = 8*8 = 64bit; $bitmap数组一共50*64 = 3200个bit位),也就是说能为最大值小于等于3200的整数集合排序 8 $a = array(1,4,3,50,34,60,100,88,200,150,300); //定义一个乱序的数组 9 10 //扫描$a中的每一个数, 将其转换为 x*64 + y 11 foreach ($a as $k => $v) { 12 $shang = $v / $int_bit_size; 13 $yushu = $v % $int_bit_size; 14 15 $offset = 1 << $yushu; 16 17 $bitmap[$shang] = $bitmap[$shang] | $offset;//将bit位置为1 18 } 19 20 //将$bitmap中的bit位依次还原为整数输出,即可得到排序后的数组 21 $b = array(); 22 foreach ($bitmap as $k => $v) { 23 for ($i = 0; $i < $int_bit_size; $i++) { 24 $tmp = 1 << $i; 25 $flag = $tmp & $bitmap[$k]; 26 27 // $b[] = $flag ? $k * $int_bit_size + $i : false; 28 if ($flag) { 29 $b[] = $k * $int_bit_size + $i; 30 } 31 } 32 } 33 34 var_dump($b);exit; 35 } 36 // 浏览器输出: 37 array 38 0 => int 1 39 1 => int 3 40 2 => int 4 41 3 => int 34 42 4 => int 50 43 5 => int 60 44 6 => int 88 45 7 => int 100 46 8 => int 150 47 9 => int 200 48 10 => int 300
求交集代码:
生成两个bitmap -> 循环两个bitmap 与操作 生成一个新的bitmap -> 还原bitmap为数字
public function sort($a = array()) { // var_dump(PHP_INT_MAX, PHP_INT_SIZE); // int 9223372036854775807 // int 8 $bitmap = array_fill(0, 50, 0); //申请一个整形数组, 50个元素, 初始化为整数0 $int_bit_size = PHP_INT_SIZE * 8; //$bitmap中每个整形的二进制位数 (本例中int = 8*8 = 64bit; $bitmap数组一共50*64 = 3200个bit位) // $a = array(1,4,3,50,34,60,100,88,200,150,300); //定一个乱序的数组 //扫描$a中的每一个数, 将其转换为 x*64 + y foreach ($a as $k => $v) { $shang = $v / $int_bit_size; $yushu = $v % $int_bit_size; $offset = 1 << $yushu; $bitmap[$shang] = $bitmap[$shang] | $offset;//将bit位置为1 } return $bitmap; } public function intersect() { $int_bit_size = PHP_INT_SIZE * 8; $a = array(1,4,3,50,34,60,100,88,200,150,300); $b = array(1,5,3,50,34,55,100,87,222,150,300); $bit_a = $this->sort($a); $bit_b = $this->sort($b); $c = array(); foreach ($bit_a as $k => $v) { $c[$k] = $bit_a[$k] & $bit_b[$k]; //二进制 & 计算求交集 } $d = array(); foreach ($c as $k => $v) { for ($i = 0; $i < $int_bit_size; $i++) { $tmp = 1 << $i; $flag = $tmp & $c[$k]; // $b[] = $flag ? $k * $int_bit_size + $i : false; if ($flag) { $d[] = $k * $int_bit_size + $i; } } } var_dump($d);exit; } 浏览器输出: array 0 => int 1 1 => int 3 2 => int 34 3 => int 50 4 => int 100 5 => int 150 6 => int 300
参考:
http://kevinbest0702.blog.163.com/blog/static/85409746201291484128939/
http://www.cnblogs.com/dolphin0520/archive/2011/10/19/2217369.html