快排 递归 非递归

我记得曾经 有一个大师说过这么一句话,大概的意思是说若是你懂得了编程,那么请你给我用非递归表达你的思想。我想非递归隐藏的东西偏偏应该是程序员应该注意的东西。由于递归的隐藏,让咱们其实没有真正的理解实现的具体细节。今天我想用非递归的方式去作一下快排。java

你们都应该知道快排:程序员

一、不稳定排序编程

二、时间复杂度:O(nlogn)。糟糕的时候时间复杂度是O(n*n)数组

思想是学习

1借用一个元素为flag 让数组左面的数组小于该flag,右面的数大于该flag。ui

2左右分割区域继续找flag递归1步骤。this

非递归的思想更可以清楚的描述快排的思想。排序

一、设置两个栈区,分别记录先后区域的初始位置和结束为止。(开始为数组的0位置和终止位置len-1)递归

二、用快排思想找到flag。而后判断先后区域是否为空,若是有一个不为空说明还有须要排序的数据。不然排序过程结束。ip

package example;

import java.util.Stack;

/**
* Created by Administrator on 2015/11/29.
*/
public class QuickSort {

public static void main(String[] args){
int[] a =new int[]{1,11,4,23,2,78,54,99,102,100,22,34};

       Stack<Integer> start =new Stack<Integer>();
       Stack<Integer> end =new Stack<Integer>();

       start.push(0);
       end.push(a.length-1);

while(!start.isEmpty()){
int start1= start.pop();
int end1 = end.pop();
int   priot=partition(a,start1,end1);
if(priot>start1+1){
               start.push(start1);
               end.push(priot-1);
           }
if(priot<=end1-1){
               start.push(priot+1);
               end.push(end1);
           }
       }
for(int i=0;i<a.length;i++){
           System.out.println(a[i]);
       }


   }

private static int partition(int[] a, int start1, int end1) {
int priot = a[start1];
int start =start1;

while(start1<end1){
while(a[start1]<priot) start1++;
while (a[end1]>priot)  end1--;
swap(a,start1,end1);
        }
       a[start1]=priot;
return start1;

   }

private static void swap(int[] a, int start1, int end1) {
int tmp=a[start1];

       a[start1]=a[end1];
       a[end1]=tmp;
   }


}

2016年8月3日

递归今天写了下,仍是总犯错啊!!!,贴出代码吧,继续学习

/**递归快排
 * @author hassop
 * @Description
 * @date 2016/8/3 0003
 * To change this template use File | Settings | File Templates.
 */
public class QuickSearch {
    /**
     * 非递归
     * @param a
     */
    static void quick(int[] a,int begin,int end){
        //终止条件
        if(begin==end){
            return;
        }

      int i=begin+1;
      int j=end;
      int k =a[begin];

      //排序过程
      while(i<j){
          while(a[j]>k){
              j--;

          }
          while(a[i]<k&&i<j){
              i++;
          }
          sweap(a,i,j);

      }
        sweap(a, begin, i);
        if((i-1)>=begin){
            quick(a,begin,i-1);
        }else {
            quick(a,begin,begin);
        }

        if((i+1)>=end){
            quick(a,end,end);

        }else{
            quick(a,i+1,end);
        }

       }

    static void sweap(int[] a,int i, int j) {
        int tmp =a[i];
        a[i]= a[j];
        a[j]=tmp;
    }


    /*psvm*/
    public static void main(String[] args) {
      int[] a ={2,1,3,4,19,5,6,8,39,21,65};
        quick(a, 0, a.length - 1);
        for(int i=0;i<a.length;i++){
            System.out.println(a[i]);
        }

    }
}
相关文章
相关标签/搜索