#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <ctime>
#include <stdlib.h>
using namespace std;
const int MAX = 1000;
vector<int> orited;//全局原始未排序vector
void randNum()
{//产生随机数存于vector
ofstream fp("data.txt");
if (fp.fail())
{
cout << "open data error " << endl;
exit(EXIT_FAILURE);
}
srand((unsigned)time(NULL));
for (int i=0 ; i<MAX ; i++)
{
orited.push_back(rand()); //是用vector保存随机数
fp << orited[i] << " ";
}
fp.close();
}
/************************************************************************/
/* 快速排序 */
/************************************************************************/
int Partion(vector<int> &v ,int low ,int high)
{//对vector进行划分,返回枢轴下标
int pivotkey;
pivotkey = v[low] ;
while ( low < high )
{
while (low < high && v[high] >= pivotkey)
high--;
v[low] = v[high];
while (low < high && v[low] <= pivotkey)
low++;
v[high] = v[low];
}
v[low] = pivotkey;
return low;
}
void quickSort(vector<int> &number, int left, int right)
{//用引用解决传参问题,以下类似
if ( left < right )
{
int i = Partion(number , left, right) ;
quickSort(number, left, i-1); // 对左边进行递归 59. quickSort(number, i+1, right); // 对右边进行递归
}
}
void quick_sort()
{//快速排序测试程序
double start ,end ;
vector<int> v(orited);//直接用全局orited初始化v
start = clock() ;
quickSort(v,0,MAX-1);
end = clock();
cout << "quick sort cost : " << end - start << endl;
}
/*********************************/
/*冒泡排序*/
/**********************************/
void bubble_sort()
{
int i, j;
vector<int> v(orited);
double start, end;
start = clock(); /*计时函数*/
for (i = 0; i< MAX; i++)
{
for (j = i + 1; j< MAX; j++)
{
if (v[i] > v[j])//最小的往左冒泡
{
swap(v[i],v[j]);
}
}
}
end = clock();
cout << "bubble sort cost : " << end - start << endl;
}
/*main函数输出时间复杂度*/
void main(){
randNum();
quick_sort();
bubble_sort();
double t = clock();
cout << t << endl;
system("pause");
}
排序算法的时间复杂度比较(quick_sort;bubble_sort)
最新推荐文章于 2024-08-17 23:37:21 发布