Heim  >  Artikel  >  Backend-Entwicklung  >  php实现插入排序,php实现排序_PHP教程

php实现插入排序,php实现排序_PHP教程

WBOY
WBOYOriginal
2016-07-13 09:59:36875Durchsuche

php实现插入排序,php实现排序

<&#63;php
/**
 * 插入排序
 * @param Array $a 无序集合
 * @return Array 有序集合
 */
function insertSort($a) {
  $temp;
  $i;
  $j;
  $size_a = count($a);
  # 从第二个元素开始
  for ($i = 1; $i < $size_a; $i++) {      
    if ($a[$i] < $a[$i-1]) {     
      $j = $i; # 保存当前元素的位置
      $temp = $a[$i]; # 当前元素的值  
 
      # 比较左边的元素,如果找到比自己更小的,向右移动元素,否则插入元素到当前位置
      while($j>0 && $temp<$a[$j-1]) {
        $a[$j] = $a[$j-1];
        $j--;
      }
       
      # 插入元素
      $a[$j] = $temp;
    }
  }
  return $a;
}
/**
 * 获取随机数
 * @param Integer $size 数量
 * @return Integer
 */
function randomNumber($size = 10) {
  $rand = array();
  srand(time(NULL));
  for ($i = 0; $i < $size; $i++) {
    array_push($rand, mt_rand(0,1000));   
  }
  return $rand;
}
 
$a = randomNumber();
echo sprintf("Unsorted list %s\n", implode(" ", $a));
echo sprintf("Sorted list %s\n", implode(" ", insertSort($a)));

以上就是本文所述的全部内容了,希望大家能够喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/975525.htmlTechArticlephp实现插入排序,php实现排序 php/** * 插入排序 * @param Array $a 无序集合 * @return Array 有序集合 */function insertSort($a) { $temp; $i; $j; $size_a = count...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn