Home  >  Article  >  Backend Development  >  php insertion sort

php insertion sort

巴扎黑
巴扎黑Original
2016-11-22 11:43:16886browse

<?php
/**
 *  InsertSort
 */
function insertSort($data){
  
  $len=count($data);
  $list = array();
  $list[0] = $data[0];
  for($i=1;$i<$len;$i++){
$list_len = count($list);
if($list[$list_len-1]<$data[$i]){
 $list[]=$data[$i];
 continue;
}
for($j=0; $j<$list_len; $j++){
 
 if($data[$i] < $list[$j]){
for($t=$list_len; $t > $j; $t--){
 $list[$t]=$list[$t-1];
}
$list[$j] = $data[$i];
break;
 }
}
  }
  return $list;
}
$data = array(9,8,7,6,5,4,3,2,1,0);
print_r(insertSort($data));

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
Previous article:PHP quick sortNext article:PHP quick sort