快速排序非递归算法的java实现
来源:互联网 发布:js取元素位置 编辑:程序博客网 时间:2024/05/20 20:56
package edu.pku.ss.hlj;import java.util.Stack;public class QuickSort { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub QuickSort t=new QuickSort(); t.test(); } public void test(){ int a[]={10,1,4,7,8,6,13,41,4,34,5,9,2}; printArray(a); nonRecrutSort(a); // nonRecrutQuickSort(a); printArray(a); } public void nonRecrutSort(int[] a){//非递归快排,两个栈 //设置两个栈,一个用于保存 if(a==null||a.length<0) return; Stack<Integer> startStack=new Stack<Integer>();//保存当前划分的最高位 Stack<Integer> endStack=new Stack<Integer>();//保存当前划分的最低位 int start=0; int end=a.length-1; int pivotPos; startStack.push(start); endStack.push(end); while(!startStack.isEmpty()){ start=startStack.pop(); end=endStack.pop(); pivotPos=partition(a, start, end); if(start<pivotPos-1){ startStack.push(start); endStack.push(pivotPos-1); } if(end>pivotPos+1){ startStack.push(pivotPos+1); endStack.push(end); } } } public void nonRecrutQuickSort(int a[]){ if(a==null||a.length<=0)return; Stack<Integer> index=new Stack<Integer>(); //用一个栈存储分界点位置的 int start=0; int end=a.length-1; int pivotPos; index.push(start); index.push(end); while(!index.isEmpty()){ end=index.pop(); start=index.pop(); pivotPos=partition(a,start,end); if(start<pivotPos-1){ index.push(start); index.push(pivotPos-1); } if(end>pivotPos+1){ index.push(pivotPos+1); index.push(end); } } } public int partition(int[] a,int start,int end){//分块方法,在数组a中,对下标从start到end的数列进行划分 int pivot=a[start]; //把比pivot(初始的pivot=a[start]小的数移动到pivot的左边 while(start<end){ //把比pivot大的数移动到pivot的右边 while(start<end&&a[end]>=pivot) end--; a[start]=a[end]; while(start<end&&a[start]<=pivot) start++; a[end]=a[start]; } a[start]=pivot; return start;//返回划分后的pivot的位置 //printArray(a); } public void printArray(int a[]){//打印数组内容的方法,用于测试 for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); } }
0 0
- 快速排序非递归算法的java实现
- 快速排序算法的非递归实现
- 快速排序的非递归算法实现
- 非递归实现快速排序算法
- JAVA实现快速排序(非递归)
- 快速排序的非递归算法
- 非递归的快速排序算法
- 快速排序的非递归算法
- 非递归的快速排序算法
- 三种快速排序算法的实现(递归算法、非递归算法、三路划分快速排序)
- 三种快速排序算法的实现(递归算法、非递归算法、三路划分快速排序)
- 三种快速排序算法的实现(递归算法、非递归算法、三路划分快速排序)
- 快速排序算法递归与非递归实现
- 快速排序算法递归和非递归实现 [# 29]
- 快速排序的非递归实现
- php的非递归快速排序实现
- 非递归的快速排序实现(转)
- 快速排序的非递归实现
- 【ObjC那点儿事儿】block练习
- 修改MySql默认编码
- 砝码称重
- sicily 1136 山海经
- Windows C++迁移Linux C++问题集锦
- 快速排序非递归算法的java实现
- Java范型浅析
- Visual Studio 2008 环境变量的配置(参考设置VS2010)
- Effective C++ 读书笔记 【持续更新】
- php 常用函数整理
- 自动化测试博客
- 使用类、类属性、对象属性
- erlang for learn
- IO流 Java核心技术读书笔记