排序函数:
#include
#include
#include
#include
int ctsort(int *data,int size,int max)
{
int *count = NULL;
int *temp = NULL;
int i = 0;
int j = 0;
if((count = (int *)malloc(max * sizeof(int))) == NULL)
{
printf("Error:Allocate storage for count!");
return -1;
}
if((temp = (int *)malloc(size * sizeof(int))) == NULL)
{
printf("Error:Allocate storage for sorted elements!");
free(count);
return -1;
}
for(i = 0;i < max;i++)
count[i] = 0;
for(i = 0;i < size;i++)
count[data[i]] += 1;
for(i = 1;i < max;i++)
count[i] = count[i] + count[i-1];
for(i = size -1;i >= 0;i--)
{
temp[count[data[i]] - 1] = data[i];
count[data[i]] -= 1;
}
memcpy(data,temp,size * sizeof(int));
free(count);
free(temp);
return 0;
}
#ifndef __CTSORT_H
#define __CTSORT_H
int ctsort(int *data,int size,int max);
#endif
生成随机数:
#include
#include
#include
#include
#include "generate.h"
void generate(int *data,int size)
{
int i = 0;
int j = 0;
int number = 0;
srand(time(NULL));
for(i = 0;i < NUM;i++)
{
number = rand()%UPPER_LIMIT;
data[i] = number;
}
}
#ifndef __GENERATE_H
#define __GENERATE_H
#define LOWER_LIMIT 0
#define UPPER_LIMIT 10
#define NUM 20
void generate(int *data,int size);
main函数:
#include
#include "generate.h"
#include "ctsort.h"
int main()
{
int array[NUM] ={0};
int i = 0;
generate(array,NUM);
printf("Before sort:\n");
for(i=0;i
printf("%d ",array[i]);
printf("\n");
ctsort(array,NUM,UPPER_LIMIT);
printf("After sort:\n");
for(i=0;i
printf("%d ",array[i]);
printf("\n");
}
MKAEFLE文件:
main:main.o generate.o ctsort.o
cc -o main main.o generate.o ctsort.o
main.o:main.c generate.h ctsort.h
cc -c main.c
generate.o:generate.c generate.h
cc -c generate.c
ctsort.o:ctsort.c ctsort.h
cc -c ctsort.c
clean:
rm *.o -rf
clear:
rm *.o main -rf
阅读(1078) | 评论(0) | 转发(0) |