• PHP实现四种排序-冒泡排序


    程序=算法+数据结构,作为一个PHP程序员,需要掌握一下。

    代码实现:

    /**
    *    冒泡排序
    *    按照两两比较大小,注意比较轮数和每轮比较次数;
    *    假设数组有n个元素,则需要n-1轮比较;每i轮比较n-i次(即 第1轮中需要n-1次比较、第2轮中需要n-2次比较...第n-1轮中需要1次比较)
    */
    function numSort($arr){
    	$mnt = count($arr);
    	if($mnt==1){
    		return $arr;
    	}
    	for ($i=0; $i < $mnt-1; $i++) { 
    		for ($j=0; $j < $mnt-1-$i; $j++) { 
    			if($arr[$j]>$arr[$j+1]){
    				$temp 	   = $arr[$j];
    				$arr[$j]   = $arr[$j+1];
    				$arr[$j+1] = $temp;
    			}
    		}
    	}
    	return $arr;
    }
    //测试
    $arr = [5,2,1,1,3,1,4];
    $end = numSort($arr);
    echo "<pre>";
    print_r($end);
    
    

    过程分析:

    第1轮:

    第1次: Array ( [0] => 2 [1] => 5 [2] => 1 [3] => 1 [4] => 3 [5] => 1 [6] => 4 )
    第2次: Array ( [0] => 2 [1] => 1 [2] => 5 [3] => 1 [4] => 3 [5] => 1 [6] => 4 )
    第3次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 5 [4] => 3 [5] => 1 [6] => 4 )
    第4次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 5 [5] => 1 [6] => 4 )
    第5次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 1 [5] => 5 [6] => 4 )
    第6次: Array ( [0] => 2 [1] => 1 [2] => 1 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )

    第2轮:

    第1次: Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
    第2次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
    第3次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => 4 [6] => 5 )
    第4次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
    第5次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )

    第3轮:

    第1次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
    第2次: Array ( [0] => 1 [1] => 1 [2] => 2 [3] => 1 [4] => 3 [5] => 4 [6] => 5 )
    第3次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
    第4次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

    第4轮:

    第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
    第2次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
    第3次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

    第5轮:

    第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )
    第2次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

    第6轮:

    第1次: Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 )

    结论:

    假设数组有n个元素,则需要n-1轮比较;每i轮比较n-i次(即 第1轮中需要n-1次比较、第2轮中需要n-2次比较...第n-1轮中需要1次比较)

  • 相关阅读:
    根正苗红_百度百科
    会员
    阴阳屏_百度百科
    腹黑正太_百度百科
    创享派-互联网创业者社区
    TF-IDF与余弦相似性的应用(一):自动提取关键词
    跑过三关六码头,吃过奉化芋艿头里的三关六码头是什么?_百度知道
    梁周洋_百度百科
    PClady专访中国第一名媛、元媛舞会总裁周采茨女士【图】_摩登前沿 _奢品 _太平洋时尚网
    AV_百度百科
  • 原文地址:https://www.cnblogs.com/meetuj/p/10407684.html
Copyright © 2020-2023  润新知