- 论坛徽章:
- 1
|
用php写了一个,排序后冒泡- <?php
- /**
- * file "lines" gives like this
- * a:0.13 b:0.23 c:0.05 d:0.45 e:0.07
- * p:0.01 q:0.20 r:0.13 s:0.33 t:0.23
- *
- * */
- $content = file_get_contents('lines');
- $rows = explode("\n",$content);
- function string2KeyedArray($string, $delimiter = " ", $kv = ":") {
- if ($a = explode($delimiter, $string)) { // create parts
- foreach ($a as $s) { // each part
- if ($s) {
- if ($pos = strpos($s, $kv)) { // key/value delimiter
- $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
- } else { // key delimiter not found
- $ka[] = trim($s);
- }
- }
- }
- return $ka;
- }
- } // string2KeyedArray
- function arrSumMax($arrSum , $sortedArr){
- if($arrSum < 0.5){ //print the line
- foreach($sortedArr as $k => $v){
- echo $k.":".$v." ";
- }
- echo "<br />";
- }
- }
- foreach($rows as $line){
- $sortedArr = string2KeyedArray($line);
- $arrSum = array_sum($sortedArr);
- arrSumMax($arrSum , $sortedArr);
- asort($sortedArr); //sort array return 1
- while($arrSum > 0.5) {
- $arrSum = array_sum($sortedArr) - array_pop($sortedArr); //pop last
- arrSumMax($arrSum , $sortedArr);
- }
- }
- ?>
复制代码 |
|