Insert Sort
Nothing likes to look at the data structure and algorithm, increase their understanding of data structure and algorithms, but also increase their programming skills. The insertion sort is one of the more common sorts, and it is very simple to understand. Now for example, the following data needs to be sorted:
10 3 8 0 6 9 2
When you use Insert sorting for ascending sorting, the steps for sorting are as follows:
10 3 8 0 6 9 2//Take element 3, go to compare with 10
3 10 8 0 6 9 2//due to 10:3, move 10 back, place 3 in the original 10 position, and then take 8 to compare with the previous element 10
3 8 10 0 6 9 2//likewise move 10; then 8 and 3, 8 greater than 3, so no longer move; so repeat.
......
0 2 3 6 8 9 10
That is, each time we take an element, we compare the element to the previously sorted element.
The worst time complexity for inserting a sort is O (n^2). At the same time, the algorithm does not need to open up additional space, it is in the original space to move operations.
Code implementation
Copy Code code as follows:
#include <iostream>
using namespace Std;
void Insertsort (int arr[], int length)
{
int temp;
for (int i = 1; i < length; ++i)//start with the second element in the array
{
temp = Arr[i]; Record the current element
int j = i-1;
while (J >= 0 && Temp < ARR[J])//Compare the current element to a previously sorted sequence element
{
Arr[j + 1] = Arr[j]; The sorted sequence is moved back in the whole.
--j;
}
Arr[j + 1] = temp; Inserts the current element
}
}
int main ()
{
int arr[10] = {9, 2, 8, 2, 3, 2, 4, 10, 34, 5};
Insertsort (arr, 10);
for (int i = 0; i < ++i)
{
cout<<arr[i]<< "";
}
cout<<endl;
return 0;
}