原创博文,转载请注明出处!

本文代码的github地址

# 基本思想

”快速排序“是对”冒泡排序“的改进。

基本原理:基于分治法,在待排线性表中取一个元素pivot作为枢轴值,通过一趟排序将待排线性表划分为独立的两部分,第一部分的所有元素小于pivot,第二部分的所有元素大于等于pivot,pivot位于其最终位置。递归对两个子表做快速排序。

# C++代码(递归和非递归)

#include <iostream>
#include <vector>
using namespace std; // 一次快速排序
int partition(vector<int> &a, int low, int high)
{
// 枢轴值(线性表第一个元素作为枢轴值)
int key = a[low];
while(low < high)
{
// 从右侧找小于pivot的值,替换low位置的元素
while(low < high && a[high] >= key)
--high;
a[low] = a[high]; // 从左侧找大于pivot的值,替换high位置的元素
while(low < high && a[low] <= key)
++low;
a[high] = a[low];
}
a[low] = key; return low;// 返回一趟排序后确定的元素位置
} //快速排序的递归形式
void QuickSort(vector<int> &a, int low, int high)
{
if(low < high)// 递归出口
{
int loc = partition(a, low, high);//一趟排序结果的调用
QuickSort(a, low, loc-1);
QuickSort(a, loc+1, high);
}
} int main()
{
vector<int> a={46,79,56,38,40,84};
QuickSort(a, 0, a.size()-1); // 打印排序后的数组
for(int i=0;i<a.size();++i)
cout<<a[i]<<' '; return 0;
}
#include <iostream>
#include <vector>
#include <stack>
using namespace std; int partion(vector<int> &root,int low,int high)
{
int part=root[low];
while(low<high)
{
while(low<high&&root[high]>part)
high--;
root[low]=root[high]; while(low<high&&root[low]<part)
low++;
root[high]=root[low];
}
root[low]=part;
return low;
} void quickSort(vector<int> &root,int low,int high)
{
stack<int> st;
int k;
if(low<high)
{
st.push(low);
st.push(high);
while(!st.empty())
{
int j=st.top();st.pop();
int i=st.top();st.pop(); k=partion(root,i,j); if(i<k-1)
{
st.push(i);
st.push(k-1);
}
if(k+1<j)
{
st.push(k+1);
st.push(j);
}
}
}
} int main()
{
vector<int> root = {4,2,6,7,9,5,1,3};
quickSort(root,0,root.size());
for(int i=0;i<8;i++)
cout<<root[i]<<endl;
return 0;
}

  

最新文章

  1. Canvas: Out of system resources
  2. 040医疗项目-模块四:采购单模块—采购单创建好之后跳转到采购单修改页面(editcgd.action)
  3. 学习笔记:HSB、HSL
  4. springmvc 中常用的注解配置使用说明
  5. Android实现发短信与打电话的功能
  6. ZOJ 2702 Unrhymable Rhymes(DP)
  7. Axis2(7):将Spring的装配JavaBean发布成WebService
  8. Http与协议TCP协议简单易懂
  9. 7.spark共享变量
  10. Java中Lock,tryLock,lockInterruptibly的区别
  11. 自主学习之RxSwift(一) -----Driver
  12. DevOps 开源工具
  13. linux安装教程
  14. Shiro笔记(四)Shiro的realm认证
  15. angularjs中阻止事件冒泡,以及指令的注意点
  16. 【驱动】MTD子系统分析
  17. WebDriver高级应用实例(1)
  18. TextureMerger1.6.6 二:Sprite Sheet的制作和使用
  19. ChainOfResponsibilityPattern(23种设计模式之一)
  20. jenkins平台通过maven方式使用sonar报大量关于html/css/js的错误解决办法

热门文章

  1. linux网络连接的查看和端口的监听
  2. Windows下如何配置apache虚拟主机
  3. 分析java进程假死状况
  4. maven项目Java resources 上面有个红叉但是代码里面并没有什么报错
  5. 使用Mysql Workbench 导入数据库提示 ERROR 1227 (42000) at line 18: Access denied; you need (at least one of) the SUPER privilege(s) for
  6. torch 深度学习 (2)
  7. scale的空白问题
  8. C++:tinyxml的使用
  9. 为eclipse EE(汉化版) 配置Tomcat服务器
  10. C++复制控制:拷贝构造函数