c语言 插入排序

Modified on: Thu, 19 Dec 2019 09:27:40 +0800 热度: 1,954 度
#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct{
    int* base;
    int len;
}List;

void init(List* list,int len)
{
    list->base=(int*) malloc(sizeof(int)*(len+1));
    list->len=len;
}

void insert(List* list)
{
    for (int i=1;i<=list->len;i++)
    {
        srand((unsigned)time(NULL)+i);
        int num=rand()%10000;
        list->base[i]=num;
    }
}

void sort(List list)
{
    int j;
    for(int i=2;i<=list.len;i++)
    {
        list.base[0]=list.base[i];
        for(j=i-1;list.base[j]>list.base[0];j--)
        {
            list.base[j+1]=list.base[j];
        }
        list.base[j+1]=list.base[0];
    }
}

void traverse(List list)
{
    for(int i=1;i<=list.len;i++)
    {
        cout<<list.base[i]<<endl;
    }
}
int main(int argc, const char * argv[]) {
    List list;
    init(&list,100);
    insert(&list);
    sort(list);
    traverse(list);
    return 0;
}

添加新评论