3、氣泡排序BubbleSort()
阿新 • • 發佈:2019-01-09
//氣泡排序 #include<iostream> #include<fstream> #include<cstdlib> #include<windows.h> #include<ctime> using namespace std; const int MAXSIZE=501;//待排序資料規模,r[0]保留,實際陣列是r[1]---r[500] //氣泡排序BubbleSort() void BubbleSort(int r[],int n) { int exchange=n; int bound=0; int temp=0;//交換函式的暫存變數 while(exchange!=0) { bound=exchange; exchange=0; for(int i=1;i<bound;i++) if(r[i]>r[i+1])//交換兩者順序 { temp=r[i+1]; r[i+1]=r[i]; r[i]=temp; exchange=i;//一趟排序時最後交換的位置 } //在該位置之後都是排序好的 } } //從外存data.txt讀取資料至記憶體陣列 void read_data(int data[]) { ifstream infile("data_salary.txt",ios::in); if(!infile) { cerr<<"open data_salary.txt error!"<<endl; system("pause"); //exit(1); } for(int i=1;i<MAXSIZE;i++) infile>>data[i]; infile.close(); } //輸出記憶體陣列至外存ordered_data_salary.txt檔案 void write_data(int data[]) { ofstream outfile("ordered_data_salary.txt",ios::out); if(!outfile) { cerr<<"open ordered_data_salary.txt error!"<<endl; system("pause"); //exit(1); } outfile<<"共用時:"<<data[0]<<"微秒"<<endl; for(int i=1;i<MAXSIZE;i++) outfile<<data[i]<<endl; outfile.close(); } //測試時間開始 inline LARGE_INTEGER time_begin() { LARGE_INTEGER start_time; QueryPerformanceCounter(&start_time);//獲取時鐘計數 return start_time; } //測試時間結束 inline LARGE_INTEGER time_end() { LARGE_INTEGER end_time; QueryPerformanceCounter(&end_time); return end_time; } //主函式 int main(void) { int data[MAXSIZE];//建立待排序資料陣列 read_data(data);//讀資料 double time_test;//計算排序測試時間 LARGE_INTEGER Freq;//64位有符號整數值 QueryPerformanceFrequency(&Freq);//獲取時鐘週期,“1次/秒”,Hz //測試時間開始 LARGE_INTEGER time1=time_begin(); //排序演算法開始 int n=MAXSIZE-1; BubbleSort(data,n); //測試時間結束 LARGE_INTEGER time2=time_end(); time_test=( (time2.QuadPart - time1.QuadPart)*1000000/Freq.QuadPart ); //此處*1000,以毫秒為單位;*1000 000以微妙為單位 cout<<"氣泡排序法:已經排好順序,請檢視:ordered_data_salary.txt檔案!"<<endl; cout<<"排序時間:"<<time_test<<" 微秒"<<endl; data[0]=time_test;//data[0]處存放排序時間 write_data(data);//寫資料 system("pause"); return 0; }