霍尔快速排序 非递归 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; }
相关文章推荐
- 霍尔快速排序 非递归 C++实现
- 快速排序的递归和非递归实现 -----C++、JAVA代码实现
- C/C++面试题(三) 推断二叉树、快速排序递归实现、递归判断数组递增
- C/C++面试题(三) 推断二叉树、快速排序递归实现、递归判断数组递增
- 快速排序C++实现(递归,非递归)
- C++ 快速排序 递归实现
- C++实现快速排序,递归写法
- 快速排序的两种实现思路和非递归实现--C++实现
- 快速排序c++实现--将未排序部分的最后一个数作为主元
- 经典算法与数据结构的c++实现——快速排序
- 快速排序 c++实现2.0
- 笔记:快速排序的java实现,递归的实现
- 快速排序的c++代码实现
- 快速排序递归及非递归实现
- java 递归实现快速排序
- 快速排序的非递归实现
- 快速排序的递归与非递归实现
- java 递归实现快速排序
- 快速排序的两重递归实现
- 算法导论 - QuickSort 快速排序 C++实现