标签:排序 递归 int 分治 quickSort privotIndex push pivot include
递归实现
#include <stdio.h> #include <string> using namespace std; int partition(int s[],int l,int r); void quickSort(int s[],int l,int r); int main(){ int s[9]={7,5,4,6,2,3,1,9,8}; quickSort(s,0,8); for(int i=0;i<9;i++) printf("%d ",s[i]); } int partition(int s[],int l,int r){ if(l>=r) return l; int pivot=s[l];//枢纽取第一个数 while(l<r){ while(l<r && s[r]>=pivot) r--;//从右开始扫描小于枢纽的 if(l<r) s[l]=s[r];//把小值换到左边 while(l<r && s[l]<=pivot) l++; if(l<r) s[r]=s[l]; } s[l]=pivot;//挖的坑记得要填上 return l;//返回枢纽位置 } void quickSort(int s[],int l,int r){ if(l<r){ int pivotIndex= partition(s,l,r); quickSort(s,l,pivotIndex-1); quickSort(s,pivotIndex+1,r); } } //参考的是QuickSort.h源码
非递归
#include <stdio.h> #include <string> #include <stack> using namespace std; int partition(int s[],int l,int r); void quickSort_stack(int s[],int n); int main(){ int s[9]={7,5,4,6,2,3,1,9,8}; quickSort_stack(s,9); for(int i=0;i<9;i++) printf("%d ",s[i]); } int partition(int s[],int l,int r){ if(l>=r) return l; int pivot=s[l];//枢纽取第一个数 while(l<r){ while(l<r && s[r]>=pivot) r--;//从右开始扫描小于枢纽的 if(l<r) s[l]=s[r];//把小值换到左边 while(l<r && s[l]<=pivot) l++; if(l<r) s[r]=s[l]; } s[l]=pivot;//挖的坑记得要填上 return l;//返回枢纽位置 } void quickSort_stack(int a[],int n){ int l=0,r=n-1; stack<int> s; s.push(l); s.push(r); while(!s.empty()){//本质上栈也是起到了保存子问题位置信息的作用 r=s.top(); s.pop(); l=s.top(); s.pop(); int privotIndex=partition(a,l,r); if(privotIndex-1>l){ s.push(l); s.push(privotIndex-1); } if(privotIndex+1<r){ s.push(privotIndex+1); s.push(r); } } }
标签:排序,递归,int,分治,quickSort,privotIndex,push,pivot,include 来源: https://www.cnblogs.com/yasheng/p/12516757.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。