一道PHP笔试题:请使用伪语言结合数据结构冒泡排序法对以下一组数据进行排序 10 2 36 14 10 25 23 85 99 45。
关于冒泡排序大家应该都非常熟悉了,原理就不多说了,这里只做简单记录。下面是参考代码。
1 <?php 2 class engage 3 { 4 public function getArray() 5 { 6 $arr1 = array ( 7 ‘0‘ => array (‘fid‘ => 1, ‘tid‘ => 1, ‘name‘ => ‘Name1‘ ), 8 ‘1‘ => array (‘fid‘ => 1, ‘tid‘ => 2 , ‘name‘ => ‘Name2‘ ), 9 ‘2‘ => array (‘fid‘ => 1, ‘tid‘ => 5 , ‘name‘ => ‘Name3‘ ), 10 ‘3‘ => array (‘fid‘ => 1, ‘tid‘ => 7 , ‘name‘ => ‘Name4‘ ), 11 ‘4‘ => array (‘fid‘ => 3, ‘tid‘ => 9, ‘name‘ => ‘Name5‘ ) 12 ); 13 $arr2 = array(); 14 foreach ($arr1 as $key => $value) 15 { 16 $arr2[$value[‘fid‘]][] = array(‘tid‘ => $value[‘tid‘],‘name‘ => $value[‘name‘]); 17 } 18 return $arr2; 19 } 20 //print_r($arr2); 21 //$eString = ‘open_door‘; 22 public function getString($eString = null) 23 { 24 $eString = explode(‘_‘,$eString); 25 $eString = array_map("ucfirst",$eString); 26 $eString = implode($eString,‘‘); 27 return $eString; 28 } 29 /** 30 * 冒泡排序 31 * @return unknown 32 */ 33 public function getBubble() 34 { 35 $isOver = false; 36 $bubbleArray = array(10,2,36,14,10,25,23,85,99,45); 37 $bubbleResult = $bubbleArray; 38 do{ 39 $bubbleArray = $bubbleResult; 40 $isOver = true; 41 foreach ($bubbleArray as $key => $value) 42 { 43 if ($value < $bubbleResult[$key-1]) 44 { 45 $bubbleResult[$key]=$bubbleResult[$key-1]; 46 $bubbleResult[$key-1]=$value; 47 $isOver = false; 48 } 49 } 50 }while (!$isOver); 51 return $bubbleResult; 52 } 53 54 } 55 56 $engage = new engage(); 57 echo ‘<pre>‘; 58 print_r($engage->getArray()); 59 echo ‘</pre>‘; 60 61 echo $engage->getString(‘make_by_nowamagic‘); 62 echo ‘<pre>‘; 63 print_r($engage->getBubble()); 64 echo ‘</pre>‘; 65 ?>
程序运行结果如下:
1 Array 2 ( 3 [1] => Array 4 ( 5 [0] => Array 6 ( 7 [tid] => 1 8 [name] => Name1 9 ) 10 11 [1] => Array 12 ( 13 [tid] => 2 14 [name] => Name2 15 ) 16 17 [2] => Array 18 ( 19 [tid] => 5 20 [name] => Name3 21 ) 22 23 [3] => Array 24 ( 25 [tid] => 7 26 [name] => Name4 27 ) 28 29 ) 30 31 [3] => Array 32 ( 33 [0] => Array 34 ( 35 [tid] => 9 36 [name] => Name5 37 ) 38 39 ) 40 41 ) 42 MakeByNowamagic 43 Array 44 ( 45 [0] => 2 46 [1] => 10 47 [2] => 10 48 [3] => 14 49 [4] => 23 50 [5] => 25 51 [6] => 36 52 [7] => 45 53 [8] => 85 54 [9] => 99 55 )
来源http://www.nowamagic.net/php/php_GetBubble.php
原文:http://www.cnblogs.com/gengyi/p/6486656.html