插入排序的几种优化及测试结果

    插入排序很简单的了,于是我将算法的优化的第一站选在了这里。《编程珠玑》在第十一章就首先讨论了这个问题:

     我写的基本版本

void insertSort1(int a[], int len) { int i; int j; int tmp; for (i = 1; i < len; i ++) for(j = i; j > 0; j--) if (a[j - 1] > a[j]) { tmp = a[j - 1]; a[j - 1] = a[j]; a[j] = tmp; } }

     《编程珠玑》给出的基本版本1:

void insertSort3(int a[], int len) { int i; int tmp; int j; for (i = 1; i < len; i ++) for(j = i; j > 0 && a[j - 1] > a[j]; j--) { tmp = a[j - 1]; a[j - 1] = a[j]; a[j] = tmp; } }

 

 区别就是在for循环的条件不一样:条件判断a[j - 1] > a[j]我放在了for循环里面,而版本1放在了for循环的判断条件里面;

《编程珠玑》给出的基本版本2:

void insertSort4(int a[], int len) { int i; int j; for (i = 1; i < len; i ++) { int t = a[i]; for (j = i; j > 0 && a[j - 1] > t; j--) a[j] = a[j - 1]; a[j] = t; } }

for循环里面只有一次赋值,而原来有3个赋值;

 

随即生成测试程序结果:

 

# include <stdio.h> # include <stdlib.h> # include <time.h> # include "chapter11.h" //chapter11.h里面定义了各个插入排序的版本 int main() { // test chapter11 srand((int)(time(0))); int len = 20000; int a[len]; int i; for (i = 0; i < len; i++) a[i] = rand()%len; clock_t start = clock(); // insertSort1(a,len); // insertSort2(a,len); // insertSort3(a,len); insertSort4(a,len); clock_t end = clock(); printf("the cost time is %ld", (long int)end - start); return 0; }

 

结果:

 

insertsort1:   the cost time is 1359

 

insertsort3:   the cost time is 1000

insertsort4:   the cost time is 578

 

 

 

 

 

 

 

 

你可能感兴趣的:(插入排序的几种优化及测试结果)