zoukankan      html  css  js  c++  java
  • 十大排序算法之选择排序(2)

    2.选择排序

    <?php
    /**
     * 基础选择排序
     *
     */
    function selectionSort($sortData)
    {
        $count = count($sortData);
        $sortCount = 0;
        for ($i = $count - 1; $i > 0; $i--) {
            $max = $i;
            for ($j = 0; $j < $i; $j++) {
                $sortCount++;
                if ($sortData[$max] < $sortData[$j]) {
                    $max = $j;
                }
            }
            if ($max != $i) {
                $temp = $sortData[$max];
                $sortData[$max] = $sortData[$i];
                $sortData[$i] = $temp;
            }
        }
        echo 'selectionSort Count:' . $sortCount;
        echo PHP_EOL;
        return $sortData;
    }
    
    /**
     * 优化1:每次取最大和最小的
     *
     */
    function selectionSort_2($sortData)
    {
        $count = count($sortData);
        $sortCount = 0;
        for ($i = $count - 1, $sortFrom = 0; $i > $sortFrom; $i--, $sortFrom++) {
            $max = $i;
            $min = $sortFrom;
            for ($j = $sortFrom; $j <= $i; $j++) {
                $sortCount++;
                if ($sortData[$max] < $sortData[$j]) {
                    $max = $j;
                }
                if ($sortData[$min] > $sortData[$j]) {
                    $min = $j;
                }
            }
            if ($min != $sortFrom) {
                $temp = $sortData[$min];
                $sortData[$min] = $sortData[$sortFrom];
                $sortData[$sortFrom] = $temp;
            }
           //此处是先排最小值的位置,所以得考虑最大值(arr[max])在最小位置(left)的情况。
            if ($max == $sortFrom){
                $max = $min;
            }
            if ($max != $i) {
                $temp = $sortData[$max];
                $sortData[$max] = $sortData[$i];
                $sortData[$i] = $temp;
            }
        }
        echo 'selectionSort_2 Count:' . $sortCount;
        echo PHP_EOL;
        return $sortData;
    }
    
    $testSortData = [3, 2, 9, 234, 3432, 43, 22, 33, 21312, 123];
    
    $sortResult = selectionSort($testSortData);
    echo 'selectionSort Result:';
    echo PHP_EOL;
    echo (implode(',', $sortResult));
    echo PHP_EOL;
    
    $sortResult = selectionSort_2($testSortData);
    echo 'selectionSort_2 Result:';
    echo PHP_EOL;
    echo (implode(',', $sortResult));
    echo PHP_EOL;
  • 相关阅读:
    黑客入侵美国一家公司夺走1500万美元?Midge建议你一定要知道
    开始使用AngularJS和ASP。NET MVC -第二部分
    MVC Tempdata,查看并保持混乱
    AngularJS ui-router
    仅限OCR图像的PDF文件。
    FxButton类
    WPF图像按钮100%在XAML
    CFlexiButton类
    一个更好的位图按钮类
    COddButton
  • 原文地址:https://www.cnblogs.com/qiye5757/p/14360368.html
Copyright © 2011-2022 走看看