比較氣泡排序和快速排序的效能
阿新 • • 發佈:2019-01-07
1.取十組隨機數,每組共200000個數,分別用氣泡排序和快速排序法排序,分別記錄所化時間。
2.程式
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctype.h> //#include <math.h> FILE *fpt; //* file point of targe void exchange(int *a,int *b) { int t=*a; *a=*b; *b=t; } void bubble_sort(int list[],int n) { int i,j; for(j=n-1; j>0; j--) for(i=0; i<j; i++) if(list[i]>list[i+1]) exchange(&list[i],&list[i+1]); } void quick_sort(int list[],int left,int right) { if (left<right) { int i=left; //from left to right int j=right; //from right to left int mid=(left+right)/2; int t=list[mid];; //the base number to compare while(1) { while (list[i]<t) i++; while (list[j]>t) j--; if(i>=j) break; exchange(&list[i++],&list[j--]); } // fprintf(fpt,"***\t"); // for(int a=0; a<40; a++) fprintf(fpt,"%d\t", list[a]); // fprintf(fpt,"***\n\n"); quick_sort(list,left,i-1); quick_sort(list,j+1,right); } } int main() { clock_t start_time, finish_time; // clock_t is a type of long int. double total_time=0; time_t t; t=time(NULL); printf("System time : %s\n",ctime(&t)); double d1,d2,d3; // FILE *fpt; //* file point of targe fpt=stdout; unsigned long n=200000; if ((fpt = fopen("out.txt", "w+")) == NULL) { printf("Can't open file :out.txt \n"); exit(1); } printf("Calculation started...\n"); int sint[n],sint2[n]; for (int c=0;c<10;c++) { start_time = clock(); // generate random int for (int i=0; i<n; i++) { srand(time(NULL)); sint[i]=rand(); sint2[i]=sint[i]; } finish_time= clock(); d1 = (double)((finish_time - start_time)) / (double)CLOCKS_PER_SEC; fprintf(fpt,"generate: %.12f second\t ",d1); //bubble sort start_time = clock(); bubble_sort(sint,n); finish_time= clock(); d2 = (double)(finish_time - start_time) / (double)CLOCKS_PER_SEC; fprintf(fpt,"bubble sort: %.12f second\t",d2); // quick sort start_time = clock(); quick_sort(sint2,0,n-1); finish_time= clock(); d3 = (double)(finish_time - start_time) / (double)CLOCKS_PER_SEC; fprintf(fpt,"quick sort: %.12f second\t", d3); int k=0; for(int i=0; i<n; i++) { if(sint[i]!=sint2[i]) { fprintf(fpt,"~~~position %d is not same.~~~\n",i); k++; } } fprintf(fpt,"mismatch: %d \n",k); total_time=total_time+d1+d2+d3; } fprintf(fpt,"total time: %f second\n", total_time); fclose(fpt); printf("\n\nCalculation finished!Please find results in out.txt.!\n\n"); t=time(NULL); printf("System time : %s\n",ctime(&t)); getch(); exit(0); return 0; }
3.結果
4.比較時間
整個程式所化時間為13分15秒,等於795秒,所以統計的total time 應該沒有問題。從兩種方法所花時間上看,快速排序有絕對的優勢。