Sort learning (b) -------- insertion sort

1. Common insertion sort

Insertion sort to find the insertion position

Direct insertion of the type:

顺序法找插入位置(直接插入)

二分插入排序

缩小增量,多遍插入排序----希尔排序

Insertion sequence is inserted when it is already in good order, and an array of storage are not sequential are unordered

Let's

Look at insertion sort

After I wrote a simple code idea is to insert an element will shift all remaining elements

#include<stdio.h>

#define MAXSIZE 20

int arr[MAXSIZE] = {3,5,8,14};

int length = 4;

//要插入的数据
void insertSort(int data)
{
    //插入排序
    int i,j;
    for(i=0;i<length;i++)
    {
        if(arr[i]>data && arr[i])
        {
            //所有元素向后移
            for(j=i;j<length;j++)
            {
                arr[j+1] = arr[i];
            }
            arr[i] = data;
        }
    }
    length++;
}

/**
  * 折半插入排序算法 2018.07.22
  */
int main()
{
    insertSort(9);
    insertSort(10);
    insertSort(12);
    int i;
    for(i=0;i<MAXSIZE;i++)
    {
        if(arr[i] == 0)
        {
            break;
        }
        printf("%d\n",arr[i]);
    }
    return 0;
}
Published 93 original articles · won praise 2 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_32783703/article/details/104238877