每天刷個演算法題20160525:快速排序的遞迴轉非遞迴解法

小飛_Xiaofei發表於2016-05-28

版權所有。所有權利保留。

歡迎轉載,轉載時請註明出處:

http://blog.csdn.net/xiaofei_it/article/details/51524798


為了防止思維僵化,每天刷個演算法題。已經刷了幾天了,現在發點程式碼。

我已經建了一個開源專案,每天的題目都在裡面:

https://github.com/Xiaofei-it/Algorithms

絕大部分演算法都是我自己寫的,沒有參考網上通用程式碼。讀者可能會覺得有的程式碼晦澀難懂,因為那是我自己的理解。

最近幾天都是在寫一些原來的東西,大多數是非遞迴。以後準備刷點DP、貪心之類的題。

下面是快速排序的遞迴轉非遞迴解法。

是不是沒有人像我這樣蛋疼地把快速排序寫成非遞迴的???

/**
 *
 * Copyright 2016 Xiaofei
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package xiaofei.algorithm;

import java.util.Stack;

/**
 * Created by Xiaofei on 16/5/25.
 *
 */
public class QuickSort {

    private static int[] array;
    
    private static void sortCorecursively(int l, int r) {
        class Element {
            int l;
            int r;
            int i;
            int state;
            //這裡用state表示通用狀態,和之前非遞迴程式碼風格不一樣。
            Element(int l, int r) {
                this.l = l;
                this.r = r;
                this.i = -1;
                this.state = 0;
            }
        }
        Stack<Element> stack = new Stack<>();
        stack.push(new Element(l, r));
        while (!stack.isEmpty()) {
            Element element = stack.peek();
            if (element.state == 0) {
                int i = element.l, j = element.r, m = array[(i + j) / 2];
                do {
                    while (array[i] < m) {
                        ++i;
                    }
                    while (m < array[j]) {
                        --j;
                    }
                    if (i <= j) {
                        int temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                        ++i;
                        --j;
                    }
                } while (i <= j);
                element.i = i;
                if (element.l < j) {
                    stack.push(new Element(element.l, j));
                }
                element.state = 1;
            } else if (element.state == 1) {
                if (element.i < element.r) {
                    stack.push(new Element(element.i, element.r));
                }
                element.state = 2;
            } else if (element.state == 2) {
                stack.pop();
            }
        }
    }

    public static void sort(int[] array) {
        QuickSort.array = array;
        sortCorecursively(0, array.length - 1);
    }

}


相關文章