(1)插入排序

/*******************************************
算法一:插入排序
算法伪代码:
insert_sort(A):
    for j <―― 1 to length[A]-1
        do key <―― A[j]
            //insert A[j] into the sorted sequence A[1...j-1]
            i <―― j-1
            while i>=0 and A[i]>key
                do A[i+1]=A[i]
                   i <―― i-1
            A[i+1] <―― key
*******************************************/
#include <stdio.h>
void insert_sort(int *arr,int n)
{
    if(n<=0 || arr==NULL)
        return;
    int i,j;
    int key;
    for(j=1;j<n;++j){
        key=arr[j];
        i=j-1;
        while(i>=0 && arr[i]>key){
            arr[i+1]=arr[i];
            i--;
        }
        arr[i+1]=key;
    }
}
int main()
{
    int arr[10]={2,21,32,43,21,54,23,122,321,234};
    insert_sort(arr,10);
    int i=0;
    for(i=0;i<10;++i)
        printf("%d ",arr[i]);
}


你可能感兴趣的:(插入排序,算法导论)