您的位置:首页 > 编程语言 > C语言/C++

霍尔快速排序 非递归 C++实现

2011-02-15 16:23 369 查看
#include<iostream>
#include<stack>

using namespace std;

typedef struct
{
int x;
int y;
}stacktype;

void swap(int a[],int m,int n)
{
int temp=a[m];
a[m]=a
;
a
=temp;
}
int part(int a[],int m,int n)
{
int i,j,k;
swap(a,(int)(m+n)/2,m+1);
if(a[m+1]>a
) swap(a,m+1,n);
if(a[m]>a
) swap(a,m,n);
if(a[m+1]>a[m]) swap(a,m+1,m);
i=m;
j=n+1;
k=a[m];
while(i<j)
{
i++;
while(a[i]<k) i++;
j--;
while(a[j]>k) j--;
if(i<j) swap(a,i,j);
}
swap(a,m,j);
return j;
}

void insertsort(int a[],int n)
{
int e;
int i;
for(int j=2;j<=n;j++)
{
e=a[j];
i=j-1;
while(e<a[i])
{
a[i+1]=a[i];
i--;
}
a[i+1]=e;
}
}

void HSort(int n,int a[],int M)
{
stack<stacktype> stackptr;
stacktype temp;
int f,t,j;
temp.x=temp.y=0;
stackptr.push(temp);
f=1;
t=n;
while(f<t)
{
j=part(a,f,t);
cout<<j<<endl<<endl;
if((j-f)<M&&(t-j)<M)
{
cout<<"<,<"<<endl<<endl;
temp=stackptr.top();
stackptr.pop();
f=temp.x;
t=temp.y;
continue;
}
if((j-f)<M&&(t-j)>=M)
{
cout<<"<,>="<<endl<<endl;
f=j+1;
continue;
}
if((j-f)>=M&&(t-j)<M)
{
cout<<">=,<"<<endl<<endl;
t=j-1;
continue;
}
if((j-f)>=M&&(t-j)>=M)
{
if(j-f>t-j)
{
cout<<">=,>=:j-f>t-j"<<endl<<endl;
temp.x=f;
temp.y=j-1;
stackptr.push(temp);
f=j+1;
}
else
{
cout<<">=,>=:j-f<t-j"<<endl<<endl;
//cout<<j<<" "<<f<<" "<<t<<endl;
temp.x=j+1;
temp.y=t;
stackptr.push(temp);
t=j-1;
}
}
}
insertsort(a,n);
}

int main()
{
const int n=200;
int a
;
for(int i=1;i<n;i++) a[i]=rand()%100;
for(int i=1;i<n;i++) cout<<a[i]<<" ";
cout << endl;
cin.get();
cout<<endl;
HSort(n-1,a,5);
cout << endl;
for(int i=1;i<n;i++) cout<<a[i]<<" ";
cin.get();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: