插入排序 【详解】

插入排序
我们先来学习一个数字进行插入排序
1,2,3,4,6,7,8,9,10,5
例如我们将5 插入到进去进行排序,只需要记录下5的下标,

#inculde<stdio.h>
void main()
{
    int a[10]={1,2,3,4,6,7,8,9,10,5};
    int i,j;
    int temp; //用来记录5的下标
    for(i=1;i<10;i++)
    {
        temp=a[9];      //用来存放5的下标 
        while(j>0&&a[j-1]>temp)    //这个判定是用来 判断插入的位置,停止在哪里 循环终止的条件
        {
            a[j]=a[j-1];     // 向前移动
            j--
        }
        a[j]=temp;    //
    
}

***************************************************
下面是乱序的插入排序
#inculde<stdio>
void main()
{
    int temp;
    int a[10]={5,1,4,9,7,5,3,4,2,8};
    int i,j;
    for(i=1;i<10;i++)
    {
        temp=e[i];
        j=i;     //下标
        while(j>0 && a[j-1]>temp)
        {
                a[j]=a[j-1];   //向前移动    
                j--;
        }
        if(j!=i)     // 判断是自己
        {
            e[j]=temp;   //进行交换
        
        }
                    
    }
}

插入排序就完成了。     
 

猜你喜欢

转载自blog.csdn.net/weixin_40989362/article/details/81120765