版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyyufenfei/article/details/79766351
参考别人的自己总结的。本人水平有限,有错误麻烦指出。
两种方法:(请忽略冒泡排序)
第一种:
#include <iostream>
#include <vector>
#include <time.h>
#include <sys/timeb.h>
#include <Windows.h>
using namespace std;
void bubble_sort1(vector<int> &t)
{
int length = t.size();
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (t[j] > t[j + 1])
{
int temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
}
}
}
}
//升级版,增加了flag判断某一循环有没有进行交换,如果没有直接结束。
void bubble_sort2(vector<int> &t)
{
int length = t.size();
for (int i = 0; i < length - 1; i++)
{
bool flag = false;
for (int j = 0; j < length - 1 - i; j++)
{
if (t[j] > t[j + 1])
{
int temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
flag = true;
}
}
if (!flag)
{
break;
}
}
}
int main()
{
DWORD start1, end1;
start1 = GetTickCount();
srand((unsigned)time(0));
vector<int> v;
for (int i = 0; i < 1700; i++)
{
v.push_back(rand());
//v.push_back(rand() % 10);//生成0到9随机数
}
bubble_sort1(v);
end1 = GetTickCount();
cout << "cost time(ms):" << end1 - start1 << endl;
return 0;
}
第二种:
#include <iostream>
#include <vector>
#include <time.h>
#include <sys/timeb.h>
#include <Windows.h>
using namespace std;
void bubble_sort1(vector<int> &t)
{
int length = t.size();
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (t[j] > t[j + 1])
{
int temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
}
}
}
}
//升级版,增加了flag判断某一循环有没有进行交换,如果没有直接结束。
void bubble_sort2(vector<int> &t)
{
int length = t.size();
for (int i = 0; i < length - 1; i++)
{
bool flag = false;
for (int j = 0; j < length - 1 - i; j++)
{
if (t[j] > t[j + 1])
{
int temp = t[j];
t[j] = t[j + 1];
t[j + 1] = temp;
flag = true;
}
}
if (!flag)
{
break;
}
}
}
int main()
{
struct timeb start, end;
ftime(&start);
srand((unsigned)time(0));
vector<int> v;
for (int i = 0; i < 1700; i++)
{
v.push_back(rand());
//v.push_back(rand() % 10);//生成0到9随机数
}
bubble_sort1(v);
ftime(&end);
cout << "cost time(ms):" << (end.time - start.time) * 1000 + (end.millitm - start.millitm) << endl;
return 0;
}