不用递归,使用栈实现快速排序(非常好理解)
来源:互联网 发布:源计划亚索多少钱淘宝 编辑:程序博客网 时间:2024/06/05 23:01
#include <stack>#include <iostream>using namespace std;void swap(int &a,int &b){int temp=a;a=b;b=temp;}int partition(int arr[],int startIndex,int endIndex){int pivot=arr[startIndex]; //枢轴int tooBigIndex=startIndex,tooSmallIndex=endIndex;while(tooBigIndex<=tooSmallIndex){while(tooBigIndex<=endIndex && arr[tooBigIndex]<=pivot)tooBigIndex++;while(arr[tooSmallIndex]>pivot) //tooSmallIndex不可能小于startIndextooSmallIndex--; //因为如果达到startIndex,将会有 //arr[tooSmallIndex]=pivotif(tooBigIndex<tooSmallIndex) //说明tooSmallIndex对应的值小于pivot,tooBigIndex对应的值大于pivotswap(arr[tooBigIndex],arr[tooSmallIndex]);}swap(arr[startIndex],arr[tooSmallIndex]); //最后交换pivotreturn tooSmallIndex;}void qsort(int arr[],int low,int high){int startIndex,endIndex,pivotIndex;pair<int,int> apair;apair.first=low;apair.second=high;stack<pair<int,int>> s;s.push(apair);while(!s.empty()){apair=s.top(); s.pop();startIndex=apair.first;endIndex=apair.second;pivotIndex=partition(arr,startIndex,endIndex);if(startIndex<pivotIndex-1) //the left have more than 1 element{apair.first=startIndex;apair.second=pivotIndex-1;s.push(apair);}if(endIndex>pivotIndex+1) //the right have more than 1 element{apair.first=pivotIndex+1;apair.second=endIndex;s.push(apair);}}}int main(){int arr[]={5,4,6,3,1,-5,34,10,8,2};qsort(arr,0,9);for(int i=0;i<10;i++)cout<<arr[i]<<" ";cout<<endl;return 0;}
0 0
- 不用递归,使用栈实现快速排序(非常好理解)
- 快速排序(递归实现)
- javaScript--快速排序实现(不用sort)
- 快速排序实现(递归+非递归)
- 使用非递归实现快速排序
- 不使用递归实现的快速排序
- 递归实现快速排序
- 快速排序+递归实现
- 递归实现快速排序
- 快速排序--递归实现
- 递归实现快速排序
- 数组的快速排序(使用栈的非递归实现)
- 快速排序的非递归实现(栈)
- 快速排序C++实现(递归,非递归)
- 快速排序的递归实现
- 快速排序的递归实现
- 快速排序非递归实现
- 快速排序非递归实现
- TI会议
- Java核心技术第3章(3)
- 单例模式
- struts2中文件上传与下载
- 数据库SQL Server 2008版本升级问题
- 不用递归,使用栈实现快速排序(非常好理解)
- C++中的头文件和源文件
- Lvs+Keepalived+MySQL Cluster架设高可用负载均衡Mysql集群
- 关于minSdkVersion,targetSdkVersion
- uva - 11809 - Floating-Point Numbers
- DS18b20详解
- 随手笔记
- EM2040D多波束采集软件SIS关于grid实时显示问题
- Java笔记---Java概要