/* *Copyright (c) 2014,烟台大学计算机控制工程学院 *All right reserved *文件名称:test.cpp *作 者:邱暖 *完成日期:2015年9月14日 *版本号 :v1.10 *问题描述:感受复杂度为O(n^2)的选择排序和复杂度为O(nlogn)的快速排序在运行时间上的差异 */
(1)复杂度是O(n^2)的选择排序程序
#include <stdio.h> #include <time.h> #include <stdlib.h> #define MAXNUM 100000 void selectsort(int a[], int n) { int i, j, k, tmp; for(i = 0; i < n-1; i++) { k = i; for(j = i+1; j < n; j++) { if(a[j] < a[k]) k = j; } if(k != j) { tmp = a[i]; a[i] = a[k]; a[k] = tmp; } } } int main() { int x[MAXNUM]; int n = 0; double t1,t2; FILE *fp; fp = fopen("numbers.txt", "r"); if(fp==NULL) { printf("打开文件错!请下载文件,并将之复制到与源程序文件同一文件夹下。\n"); exit(1); } while(fscanf(fp, "%d", &x[n])!=EOF) n++; printf("数据量:%d, 开始排序....", n); t1=time(0); selectsort(x, n); t2=time(0); printf("用时 %d 秒!", (int)(t2-t1)); fclose(fp); return 0; }
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">运行结果:</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"><img src="http://img.blog.csdn.net/20150914170819324?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="367" height="192" alt="" /></span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">(2)复杂度为O(nlogn)的快速排序程序</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span><pre class="cpp" name="code">#include <stdio.h> #include <time.h> #include <stdlib.h> #define MAXNUM 100000 void quicksort(int data[],int first,int last) { int i, j, t, base; if (first>last) return; base=data[first]; i=first; j=last; while(i!=j) { while(data[j]>=base && i<j) j--; while(data[i]<=base && i<j) i++; /*交换两个数*/ if(i<j) { t=data[i]; data[i]=data[j]; data[j]=t; } } data[first]=data[i]; data[i]=base; quicksort(data,first,i-1); quicksort(data,i+1,last); } int main() { int x[MAXNUM]; int n = 0; double t1,t2; FILE *fp; fp = fopen("numbers.txt", "r"); if(fp==NULL) { printf("打开文件错!请下载文件,并将之复制到与源程序文件同一文件夹下。\n"); exit(1); } while(fscanf(fp, "%d", &x[n])!=EOF) n++; printf("数据量:%d, 开始排序....", n); t1=time(0); quicksort(x, 0, n-1); t2=time(0); printf("用时 %d 秒!", (int)(t2-t1)); fclose(fp); return 0; }
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">运行结果:</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"><img src="http://img.blog.csdn.net/20150914171313847?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" width="375" height="226" alt="" /></span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">学习心得:</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"> 通过对比两种程序的运行结果可以看出,复杂度是O(n^2)的选择排序的运行时间</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff">比复杂度是O(nlogn)d的快速排序的运行时间要长。因此,我们不仅可以得到复杂度与运行时间成正比。</span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>
<span style="font-family:Arial;BACKGROUND-COLOR: #ffffff"></span>