gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:55:08 26 4
gpt4 key购买 nike

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

最佳答案

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com