Sorting algorithms are of various kinds, each with its own strengths, these days will be analyzed. Learning should have a progressive process, from easy to start.
First say simpler-insert sort (implemented by PHP code, here is not fastidious!) )
/**
* Insert sort--sort algorithm that is slightly more complex than bubbling *
*
**/
$array = Array (' 5 ', ' 6 ', ' 3 ', ' 1 ', ' 2 ', ' 4 ');
/**
* Insert Sort 1--use the most violent sort
*
**/
function Insertsort ($array)
{
$count = count ($array); First take out a data most compare data
for ($i =1; $i < $count; $i + +)
{
$key = $array [$i];
$j = $i-1;
while ($j >=0 && $array [$j]> $key)
{
$array [$j +1] = $array [$j];
$j = $j-1;
$array [$j +1] = $key;
}
Var_dump ($array);
}
}
Insertsort ($array);
The following are the results of the operation:
Well, the whole algorithm is over! If you only want the code. Now that you've done your job, start talking about principles.
The insertion sort is called the insertion sort, and we can visualize it as:
When you touch the cards, the cards in your hand are in order, and the cards you touch from the stacks are random, and you just have to compare them with the cards in your hand to determine where the new cards are.
The logic of the insertion sort can be simply understood to be compared to the first element, starting with the second element, and if the element is smaller than the one, it is inserted before the first element
If it is large, compare it to the second element, and so on. (as you can see from the effect diagram)
Let's take a look at the timing of the insert sort:
In the best case, all the N-1 elements need only be compared with the preceding elements, then the time complexity is n-1;
The worst diligent, all N-1 elements need to be compared with all the previous elements, then the time complexity is a arithmetic progression ((n-1) * (n-2))/2+ (n-1);
To sum up: the time complexity of the insertion sort should be between these two.
Space complexity: Insertion ordering is a linear sort. All space complexity is related to n involved in ordering.