Home >php教程 >php手册 >php判断数组是否有序

php判断数组是否有序

WBOY
WBOYOriginal
2016-06-13 10:52:231472browse

今天就是国庆长假的最后一天,无心搞业务代码,看到群里讨论php如何判断数组有序,我就给实现了一个复杂度为N的算法,贴出代码供大家学习

[php]
function JudegSortArray($array) { 
    if ($array [0] > $array [1]) { 
        $flag = 1; 
    } else { 
        $flag = 0; 
    } 
    $temp = $flag; 
    $len = count ( $array ); 
    for($i = 1; $i         if ($flag == 0) { 
            if ($array [$i]  
            { 
                continue; 
            } else { 
                 
                $flag = 1; 
                break; 
            } 
        } 
        if ($flag == 1) { 
            if ($array [$i] > $array [$i + 1]) { 
                continue; 
            } else  
 
            { 
                $flag = 0; 
                break; 
            } 
        } 
    } 
    if ($flag != $temp) { 
        echo "无序数组"; 
    } else { 
        echo "有序数组"; 
    } 

 
// 测试用例 
$array = array ( 
        1, 
        2, 
        3, 
        4, 
        6, 
        5  
); 
$ret = JudegSortArray ( $array ); 
echo $ret; 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn