Direct insertion sort (Insert Sort)

Direct insertion sort

Ideas Analysis: find the specified insertion position for the element to be inserted in an ordered array, but this position is not necessarily the final position of the last sorting results of the corresponding elements.

Time complexity: (the entire reverse sequence) worst case time complexity of O (n ^ 2), where the optimal (the entire sequence of the original order, when descending) time complexity of O (n).

Source:

void InsertSort(int R[],int n)
{
    int i,j,temp;
    for(i=1;i<n;i++)    //插入排序共需要插入n个元素,但此处我们默认序列中存在R[0]这个元素,故之后需进行n-1次插入操作
    {
        temp=R[i];
        j=i-1;
        while(j>=0&&temp<R[j])    //比插入元素大的元素进行后移操作
        {
            R[j+1]=R[j];
            --j;
        }
        R[j+1]=temp;    //插入要插入的元素
    }
}

Guess you like

Origin www.cnblogs.com/sunnylux/p/11039332.html
Recommended