排序方法之插入排序

排序方法之插入排序


插入排序的思想重點是如果插入在中間 那麼需要將元素後移,插入的時候就排好順序
 

#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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章