Home  >  Article  >  Backend Development  >  How to implement insertion sort using PHP? _PHP Tutorial

How to implement insertion sort using PHP? _PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:12:31803browse

The basic operation of insertion sort is to insert a piece of data into the already sorted ordered data, thereby obtaining a new ordered data with the number plus one.

Algorithm description:

⒈ Starting from the first element, the element can be considered to have been sorted

⒉ Take out the next element and scan from back to front in the sorted element sequence

⒊ If the element (sorted) is larger than the new element, move the element to the next position

⒋ Repeat step 3 until you find the position where the sorted element is less than or equal to the new element

⒌ Insert the new element into the next position

⒍ Repeat step 2

Copy code The code is as follows:

$arr =array(123,0,5,-1,4,15);

function insertSort(&$arr){

//First default that the first number with subscript 0 is the arranged number
for($i=1;$i//OK Insert the compared number
$insertVal=$arr[$i];
//Confirm and compare with the previous compared number
$insertIndex=$i-1;

//Indicates none Find the position
while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){

//Move the number back
$arr[$insertIndex+1]=$arr[$insertIndex];
$insertIndex--;
}

//Insert (find the position for $insertval)
$arr[$insertIndex+1] = $insertVal;
}
}

insertSort($arr);
print_r($arr);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326657.htmlTechArticleThe basic operation of insertion sort is to insert a data into the sorted ordered data to get a New, ordered data with the number plus one. Algorithm description: ⒈ From the first...
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