PHP implements the Insertion sorting algorithm. InsertionSort is a stable, simple, and intuitive sorting algorithm. Insert sorting is a stable, simple, and intuitive sorting algorithm that builds an ordered sequence. for unordered data, insert sorting (Insertion Sort. The principle of insert sorting is to build an ordered sequence. for unordered data, scan the sequence from the back to the front to locate the appropriate position and insert it. Insert sorting. in the best case, the time complexity is O (n); in the worst case, the time complexity is O (n2); and the average time complexity is O (n2 ).
Example of inserting a sort chart:
/**
* Data structure and algorithm (implemented in PHP)-Insertion Sort ).
*
* @ Author creative programming (TOPPHP. ORG)
* @ Copyright Copyright (c) 2013 Creative Programming (TOPPHP. ORG) All Rights Reserved
* @ License http://www.opensource.org/licenses/mit-license.php MIT LICENSE
* @ Version 1.0.0-Build20130613
*/
Class InsertionSort {
/**
* Array of data to be sorted.
*
* @ Var array
*/
Private $ data;
/**
* The length of the data array.
*
* @ Var integer
*/
Private $ size;
/**
* Whether the data array is sorted.
*
* @ Var boolean
*/
Private $ done;
/**
* Constructor-initialize data.
*
* @ Param array $ array of data to be sorted.
*/
Public function _ construct (array $ data ){
$ This-> data = $ data;
$ This-> size = count ($ this-> data );
$ This-> done = FALSE;
}
/**
* Insert sorting.
*/
Private function sort (){
$ This-> done = TRUE;
For ($ I = 1; $ I <$ this-> size; ++ $ I ){
$ Current = $ this-> data [$ I];
If ($ current <$ this-> data [$ I-1]) {
For ($ j = $ I-1; $ j >=0 & $ this-> data [$ j]> $ current; -- $ j ){
$ This-> data [$ j + 1] = $ this-> data [$ j];
}
$ This-> data [$ j + 1] = $ current;
}
}
}
/**
* Obtain the sorted data array.
*
* @ Return array returns the sorted data array.
*/
Public function getResult (){
If ($ this-> done ){
Return $ this-> data;
}
$ This-> sort ();
Return $ this-> data;
}
}
?>
Sample Code 1
2
3
4 $ Insertion = new InsertionSort (array (9, 1, 5, 3, 2, 8, 6 ));
Echo'
', print_r($insertion->getResult(), TRUE), '
';
?>
Sort (Insertion Sort) is a stable, simple, and intuitive sorting algorithm. The principle of Insertion sorting is to build an ordered sequence. for unordered data, in order...