C语言之排序算法---选择法排序

来源:互联网 发布:穆雅斓的淘宝店怎么了 编辑:程序博客网 时间:2024/06/06 00:11
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ARRAYNUM 10
int *SortarrayCreate(int num)
{
    int *ptr=(int *)calloc(num,sizeof(int));
    if(!ptr)
    {
       printf("calloc failed!\n");
       exit(EXIT_FAILURE);
    }
    for(int i=0;i<num;i++)
    {
        srand(rand());
        *(ptr+i)=rand();
    }
    return ptr;
}
void sort(int *ptr,int num)
{
    int ThisLoopMin=0;
    int i=0,j=0;
    int ThisLoopMinindex;
    int ischange=0;
    for(i=0;i<num-1;i++)
    {
        ThisLoopMin=*(ptr+i);
        ThisLoopMinindex=i;
        ischange=0;
        for(j=i+1;j<num;j++)
        {
            if(*(ptr+j)<ThisLoopMin)
            {
                ThisLoopMin=*(ptr+j);
                ThisLoopMinindex=j;
                ischange=1;
            }
        }
        if(ischange)
        {
            int tmp=0;
            tmp=*(ptr+i);
            *(ptr+i)=*(ptr+ThisLoopMinindex);
            *(ptr+ThisLoopMinindex)=tmp;
        }
    }
}
int main(int argc,char **argv)
{
    int *ptr=NULL;
    time_t start,end;
    ptr=SortarrayCreate(ARRAYNUM);
    printf("The rand array before sort as follows:\n");
    for(int i=0;i<ARRAYNUM;i++)
    {
        printf("%d ",*(ptr+i));
    }
    printf("\n\n\nAfter sort the array element as follows:\n");
    sort(ptr,ARRAYNUM);
    for(int i=0;i<ARRAYNUM;i++)
    {
        printf("%d ",*(ptr+i));
    }
    free(ptr);
}
原创粉丝点击