每天刷个算法题20160525:快速排序的递归转非递归解法

版权所有。所有权利保留。

欢迎转载,转载时请注明出处:

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);
    }

}


你可能感兴趣的:(算法,递归,快速排序,ACM,非递归)