Quicksort recursive and non-recursive

Quick Sort

  • A pivot element takes benchmark
  • The elements smaller than the pivot to put the left, put the right elements greater than the pivot
  • A second step of generating left and right sections of the same operation until the sorting is completed

Recursive

Recursive easy to understand, the main idea is to continue for about two sub-intervals until the sorting is done quickly sort through recursion.

    public int[] quickSort(int[]arr){
        quickSort(arr,0, arr.length-1);
        return arr;
    }
    private int[] quickSort(int[]arr, int left, int right){
        if(left<right){
            int q = media(arr, left, right);
            quickSort(arr, left, q - 1);
            quickSort(arr, q + 1, right);
        }
        return arr;
    }
    private int media(int[]arr, int left, int right){
        int tmp = arr[right];
        int i = left;
        for(int j=left;j<right;j++){
            if(arr[j]<tmp){
                int x = arr[j];
                arr[j] = arr[i];
                arr[i] = x;
                i++;
            }
        }
        int x = arr[right];
        arr[right] = arr[i];
        arr[i] = x;
        return i;
    }

Non-recursive

It is necessary to save about artificially subintervals of the words of the non-recursive. The recursive procedure was changed to a non-recursive program, first of all we can think of using the stack, because the recursive always been a push a process stack.

    public int[] quickSort(int[]arr){
        Stack<Integer> stack = new Stack<>();
        int left = 0, right = arr.length - 1;
        stack.push(left);
        stack.push(right);
        while (!stack.isEmpty()){
            right = stack.pop();
            left = stack.pop();
            int tmp = arr[right];
            int i = left;
            for(int j=left;j<right;j++){
                if(arr[j]<tmp){
                    int x = arr[j];
                    arr[j] = arr[i];
                    arr[i] = x;
                    i++;
                }
            }
            int x = arr[right];
            arr[right] = arr[i];
            arr[i] = x;
            if(i-1>left) {
                stack.push(left);
                stack.push(i - 1);
            }
            if(i+1<right) {
                stack.push(i + 1);
                stack.push(right);
            }
        }
        return arr;
    }

 

Published 19 original articles · won praise 15 · views 50000 +

Guess you like

Origin blog.csdn.net/Juicewyh/article/details/104050277