java - 使用一种方法进行快速排序

标签 java

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

最佳答案

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

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

关于java - 使用一种方法进行快速排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245401/

相关文章:

java - 为未分配/可选参数设置随机值

java - 如何知道 boolean 值是否根本没有被设置(或取消设置)?

java - JOptionPane 列表操作

java - 函数参数 Class<Type> 不接受类型的子代

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 为什么Exception将Throwable作为构造函数参数而不是Exception?

java - 当监听器是类变量时,JPanel.addComponentListener 不起作用

java - Mockito 模拟具有相似签名的相同命名方法

java - 您如何使用 Java 制作网站?

java - 用于查找后面或前面有特殊字符的单词位置的正则表达式