Sorting algorithm - 3 direct insertion sorting algorithm

Insertion sorting: Each step inserts a piece of data to be sorted into the ordered sequence that has been sorted before, until all elements are inserted.

Time complexity: The average time complexity is O(n^2).

Algorithm steps: a[5]={3, 7, 1, 8, 5}

1) The first element of the sequence to be sorted is regarded as an ordered sequence, and the other elements are regarded as sequences to be sorted;

  3 7,1,8,5
  ordered sequence sequence to be sorted

2) Take out the first element [7] of the sequence to be sorted, and compare it with the element [3] of the ordered sequence from back to front. If the element [3] in the ordered sequence is larger than the element to be sorted, move the ordered element [3] to the next position (that is, the position of the element to be sorted [7]);

Here, if 3<7, it will not move;

3,7 1,8,5
ordered sequence sequence to be sorted

3) Then take out the element [1] in the sequence to be sorted, and compare it with the ordered sequence element [3, 7] from back to front. First, the ordered sequence element [7] is greater than the element [1] to be sorted, then there will be The sequence element [7] moves to the next position;

3,_,7 8,5
Ordered sequence, [7] moves backward, and the element to be sorted [1] is placed in the middle amount column to be sorted

Then the element [1] to be sorted is compared with other elements of the ordered element in turn, [3] is smaller than [1], the ordered element [3] is moved to the next position, and all elements of the ordered sequence are compared with the elements to be sorted Finished, place the element to be arranged in the vacant position (the position of the original ordered element);

_,3,7 8,5
ordered sequence, [3] moving backwards column to be sorted
1,3,7 8,5
Ordered sequence, put [1] in the vacant position column to be sorted

4) Continue to insert the column to be sorted into the ordered sequence according to the above method

1,3,7,8 5
1,3,7,_,8 To be sorted[5]<sorted[8], move [8] backward
1,3,_,7,8 To be arranged [5] <ordered [7], move [7] backward
1,3,5,7,8 To be arranged[5]>Ordered[3], stop moving
ordered sequence  

Code:

#include<stdio.h>
void insertsort(int a[],int len)
{
    int i,j;
    int temp;
    for(i=1;i<len;i++) //外层循环i控制待排序元素
    {
        temp=a[i];   //待排元素赋给中间量temp
        for(j=i-1;j>=0 && a[j]>temp;j--)
        { //内层循环j控制已排序的元素,同时判断待排序元素与已排好元素的大小
            a[j+1]=a[j]; //若判断成立,则将已排好元素的位置向后移动
        }
        a[j+1]=temp;     //将当前待排序元素放在空缺的位置上
    }
}

int main()
{
    int i,len;
    int a[]={3,7,1,8,5};
    len=sizeof(a)/sizeof(a[0]);  //计算数组元素个数
    printf("排序前:");
    for(i=0;i<len;i++)
    {
        printf("%d ",a[i]);
    }
    insertsort(a,len);
    printf("\n排序后:");
    for(i=0;i<len;i++)
    {
        printf("%d ",a[i]);
    }
    while (1);    
}

operation result:

Guess you like

Origin blog.csdn.net/Healer19/article/details/117448567