您的位置:首页 > 其它

快速排序(递归,非递归),希尔排序,冒泡排序的比较

2012-11-28 11:46 260 查看
数据量:100w整型数组

代码如下:

#include <iostream>
#include <stack>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;

template <typename Comparable>
int partition(vector<Comparable> &vec, int low, int high)
{
Comparable pivot = vec[low];
while(low<high)
{
while(low<high && vec[high]>=pivot)
high--;
vec[low] = vec[high];

while(low<high && vec[low]<=pivot)
low++;
vec[high] = vec[low];
}
vec[low] = pivot;
return low;
}
template <typename Comparable>
void quickSortRecursion(vector<Comparable> &vec, int low, int high)
{
if(low>=high)return ;

int mid = partition(vec, low, high);
quickSortRecursion(vec, low, mid-1);
quickSortRecursion(vec, mid+1, high);
}
template <typename Comparable>
void quickSortNonRecursion(vector<Comparable> &vec, int low, int high)
{
if(low>=high)return ;
stack<int> st;
int mid = partition(vec, low, high);
if(low<mid-1)
{
st.push(low);
st.push(mid-1);
}
if(mid+1<high)
{
st.push(mid+1);
st.push(high);
}
while(!st.empty())
{
high = st.top();
st.pop();
low = st.top();
st.pop();
mid = partition(vec, low, high);
if(low<mid-1)
{
st.push(low);
st.push(mid-1);
}
if(mid+1<high)
{
st.push(mid+1);
st.push(high);
}
}
}
template <typename Comparable>
void bubble(vector<Comparable> &vec)
{
int len = vec.size();
//vector<int> vec;
Comparable tmp;
for(int i=0; i<len; i++)
{
for(int j=i+1; j<len; j++)
{
if(vec.at(i)>vec.at(j))
{
tmp = vec.at(i);
vec.at(i) = vec.at(j);
vec.at(j) = tmp;
}
}
}
}

template <typename Comparable>
void shellSort(vector<Comparable> &vec)
{
int len = vec.size();
int grap = 0;
int i,j;
while(grap<len)
{
grap = grap*3 + 1;
}
while(grap>0)
{
for(i=grap; i<len; i++)
{
Comparable tmp = vec.at(i);
j = i - grap;
while(j>=0 && vec.at(j)>tmp)
{
vec.at(j+grap) = vec.at(j);
j -= grap;
}
vec.at(j+grap) = tmp;
}
grap = (grap-1)/3;
}

}

int main()
{
int len = 1000000;
vector<int> vec;

int i;
for(i=0; i<len; i++)
vec.push_back(rand());

clock_t t1 = clock();
quickSortRecursion(vec, 0, len-1);
clock_t t2 = clock();

cout<<"quick sort Recursive :"<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;

random_shuffle(vec.begin(), vec.end());

t1 = clock();
quickSortNonRecursion(vec, 0, len-1);
t2 = clock();

cout<<"quick sort None Recursive :"<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;

random_shuffle(vec.begin(), vec.end());

t1 = clock();
shellSort(vec);
t2 = clock();

cout<<"shellSort :"<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;

random_shuffle(vec.begin(), vec.end());

t1 = clock();
bubble(vec);
t2 = clock();

cout<<"Bubble :"<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;

cout<<"End"<<endl;
return 0;
}

测试结果(时间s):

linux,Intel Xoen CPU 2.4GHz,Mem 2G

quick sort Recursive :1.66

quick sort None Recursive :1.76

shellSort :14.73

Bubble :unknown

Win7,Intel Pentium Dual 2GHz,Mem 2G

quick sort Recursive :7.529

quick sort None Recursive :14.569

shellSort :552.917

Bubble :unknown
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐