The basic idea of a direct insert sort (straight insertion sorting) is to look at the N-sorted elements as an ordered table and an unordered table, beginning with an ordered table containing only one element, and an unordered table containing n-1 elements. Each time the first element is taken out of an unordered table, it is inserted into the appropriate position in the ordered table, making it a new ordered table, repeating n-1 times to complete the sorting process.
Insert A[i] into the a[0],a[1],...,a[i-1] the specific implementation of the process is: first assign the a[i] to the variable t, and then T and A[i-1],a[i-2],... Compare, move an element that is larger than t to the right one position until a J (0<=j<=i-1) is found, so that a[j]<=t or J is (-1) and the T is assigned to A[J+1].
An improved approach
An alternate way to find comparison operations and record move operations.
Specific practices:
The keywords to insert record r[i] are compared from right to left with the keywords in the ordered area record R[j] (j=i-1,i-2,...,1):
① if the keyword of r[j] is greater than r[i], then the r[j] is shifted back one position;
② if the keyword of r[j] is less than or equal to R[i], then the find process ends and j+1 is the insertion position of r[i].
The key is larger than the r[i] key word has been moved, so the j+1 position has been vacated, as long as the r[i] directly into this location to complete a direct insertion of the sort.
That is, the comparison begins at the back of the new sequence and shifts;
PHP Code:
[PHP]
Echo '
';
$arr = Array (90,5,3,9,2,6,10,30,0,0,0,0,0);
Print_r (Insertsort ($arr));
function Insertsort ($arr) {
$res = Array ();//space to insert
$res [0] = $arr [0];//first word descriptors in
for ($i =1; $i
$c = count ($res);//Calculation cycle count
for ($j = $c; $j >=0; $j--) {
if ($res [$j -1]<= $arr [$i]) {//$j-1 is the value to compare, $j is empty out of the bit that is about to be inserted
$res [$j] = $arr [$i];
break;//has inserted the value into the for loop that ends this value
}else{
$res [$j] = $res [$j -1];//for backward shift
}
}
}
return $res;
}
?>
Author: dats0407http://www.bkjia.com/PHPjc/478117.html www.bkjia.com true http://www.bkjia.com/PHPjc/478117.html techarticle The basic idea of a direct insert sort (straight insertion sorting) is to look at the N-sorted elements as an ordered table and an unordered table, beginning with an ordered table containing only one element ...