首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用一种方法进行快速排序

问使用一种方法进行快速排序
EN

Stack Overflow用户
提问于 2019-01-18 06:48:46
回答 1查看 344关注 0票数 1

我的教授要求我使用快速排序算法对整数数组进行排序,但没有对使用方法进行优化。他说,程序必须包含在一种方法上。我的问题是,这是可能的吗?如果是这样,你们中的任何一个人都可以演示,因为他只教了我们关于冒泡排序算法的知识。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-18 07:35:35

是的,这可以用一种方法来完成。整个递归可以通过使用循环和堆栈来迭代完成。因此,快速排序算法可以重写为:

代码语言:javascript
复制
public class Main {

    @FunctionalInterface
    public interface Func {
        void call(int[] arr, int i, int j);
    }

    public static void main(String[] args) {
        int[] numbers = {45, 123, 12, 3, 656, 32};
        System.out.println("Unsorted array: " + Arrays.toString(numbers));

        // store swap function as a lambda to avoid code duplication
        Func swap = (int[] arr, int i, int j) -> {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        };

        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        stack.push(numbers.length);

        while (!stack.isEmpty()) {
            int end = stack.pop();
            int start = stack.pop();
            if (end - start < 2) {
                continue;
            }

            // partitioning part
            int position = start + ((end - start) / 2);
            int low = start;
            int high = end - 2;
            int piv = numbers[position];
            swap.call(numbers, position, end - 1);
            while (low < high) {
                if (numbers[low] < piv) {
                    low++;
                } else if (numbers[high] >= piv) {
                    high--;
                } else {
                    swap.call(numbers, low, high);
                }
            }
            position = high;
            if (numbers[high] < piv) {
                position++;
            }
            swap.call(numbers, end - 1, position);
            // end partitioning part

            stack.push(position + 1);
            stack.push(end);
            stack.push(start);
            stack.push(position);
        }

        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }
}  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54245401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档