The direct insertion sort time is O (n^2), and the space complexity is O (1), which is a stable sorting method. Direct insertion sorting is the best way to sort records when the records in the sequence are basically ordered or less to be sorted. However, when the number of records to be sorted is low, a large number of comparisons and moves are less efficient than the direct insertion of the sorting algorithm.
Basic idea: the records are divided into ordered area and unordered area, the orderly area at the beginning is a[0], the disorder area is a[1,2,3...n-1], and then the records in the disordered area are inserted into the ordered area sequentially.
Direct insertion Sort
#include <iostream>
using namespace std;
void Directinsertsort (int a[],int n)
{
int i;
for (i = 1; I <n; i++) //unordered area
{
if (A[i]<a[i-1]) {//bright spot, preceded by the maximum value of the ordered area, if greater than this value, this loop does not need to do insert operation, avoid unnecessary comparison
int temp=a[i];//temp as "Sentinel" for
(int j=i-1;temp<a[j];j--) A[j+1]=a[j] in the course of the staging unit of the record to be inserted and the insertion location of the lookup record;
A[j+1]=temp
}
}} void Main ()
{
int a[6]={2,9,1,6,3,8};
Directinsertsort (a,6);
for (int i=0;i<6;i++)
cout<<a[i]<< "";
cout<<endl;
}
The results of the operation are as follows: