排序方法之插入排序

排序方法之插入排序


插入排序的思想重点是如果插入在中间 那么需要将元素后移,插入的时候就排好顺序
 

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>


#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define MAXSIZE 20

typedef int KeyType;

typedef struct{
    KeyType key;

}RedType;//record type

typedef struct{
    RedType r[MAXSIZE+1];//0是做哨兵或者缓冲区的
    int length;
}SqList;

void
print_array(int array[], int n)
{
    int i;

    for(i = 0; i < n; i++)
        printf("%d ", array[i]);
    printf("\n");
}

//插入排序
void
insertion_sort(int array[], int n)
{
    int j, p;
    int tmp;

    //从前往后找
    for(p=1;p<n;p++)
    {
        tmp = array[p];
        for(j=p;j>0 && array[j-1] > tmp;j--)
        {
            array[j] = array[j-1];
        }
        array[j] = tmp;
    }
}


int main()
{
    {8,32,34,51,64}
    int array[] = {34, 8, 64, 51, 32, 21};

    printf("Before sorted:");
    print_array(array, 6);
    insertion_sort(array, 6);
    printf("After sorted :");
    print_array(array, 6);

    return 0;
}
发布了93 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_32783703/article/details/104095038