排序问题专辑-前奏

来源:互联网 发布:js 数组比较相同 编辑:程序博客网 时间:2024/06/04 20:02

在随后的各个排序算法中,都假设数组内只包含整数,都属于内部排序。

用c语言实现。

之后的排序算法主要包括:

  1. 插入排序
  2. 冒泡排序
  3. 希尔排序
  4. 堆排序
  5. 归并排序
  6. 快速排序

并且生成一个包含1000000个0-2000000的随机数字的文件对各个排序算法进行时间测试。

通过对十万的随机数据进行测试,发现连续执行程序的时候程序时间是递增的,而且程序执行过程中电脑风扇声音很大,说明了处理大批数据会导致处理器发热,从而影响了处理器性能,因此对一百万的数据进行测试的话,测量的时间并不准确(不仅仅依赖于处理器的数据指标,数据量依赖于电脑配置:L)。所以我都是执行一次之后等风扇安静下来之后才执行第二次哭

生成随机数文件源码如下:

/*************************************************************************> File Name: produce_random.c> Author: W> Mail: gxxxxxxx@xx.com > Created Time: 2016年04月09日 星期六 16时14分37秒 ************************************************************************/#include<stdio.h>#include<stdlib.h>#include<time.h>#define COUNT 1000000int main(void){int i;FILE *fp;srand((unsigned)time(NULL));if((fp=fopen("rand_num.txt","w+")) == NULL){printf("Can't open file\n");exit(1);}for(i = 0; i < COUNT; i++){fprintf(fp,"%d ",rand()%2000000);}fclose(fp);return 0;}
调用系统时间对排序计时(微妙),源码如下:

/*************************************************************************> File Name: get_time.c> Author: W> Mail: gxxxxxxx@xx.com > Created Time: 2016年04月09日 星期六 16时46分19秒 ************************************************************************/#include<stdio.h>#include<sys/time.h>#include<unistd.h>int main(void){struct timeval start, end;gettimeofday(&start, NULL);sleep(3);gettimeofday(&end, NULL);int timeuse = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;printf("time: %d us\n",timeuse);return 0;}

测试程序源码:

Int main(void){int arr[NUM_COUNT] = {0};int i, count;struct timeval start, end;int used_time;FILE *in_file, *out_file;if((in_file = fopen("rand_num.txt","r")) == NULL){printf("error:open the input file failed!\n");exit(1);}if((out_file = fopen("sort_num.txt","w+")) == NULL){printf("error:open the input file failed!\n");exit(1);}count = NUM_COUNT;for(i = 0; i < count; i++){fscanf(in_file, "%d", &arr[i]);}gettimeofday(&start, NULL);sort(arr,count);gettimeofday(&end, NULL);used_time = 1000000 * (end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;printf("The sort time: %d us\n",used_time);for(i = 0; i < count; i++){fprintf(out_file, "%d ", arr[i]);}fclose(in_file);fclose(out_file);return 0;}
详细的源码在:https://github.com/GkWangBin/structures


1 0
原创粉丝点击