Java中快速排序算法的遞歸和非遞歸實(shí)現(xiàn)都是常見的排序方法。下面分別給出兩種實(shí)現(xiàn)方式的代碼示例:
public class QuickSortRecursive {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr, int low, int high) {
if (low< high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j< high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
import java.util.Arrays;
import java.util.Stack;
public class QuickSortNonRecursive {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
quickSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
stack.push(arr.length - 1);
while (!stack.isEmpty()) {
int high = stack.pop();
int low = stack.pop();
if (low< high) {
int pivotIndex = partition(arr, low, high);
stack.push(low);
stack.push(pivotIndex - 1);
stack.push(pivotIndex + 1);
stack.push(high);
}
}
}
public static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j< high; j++) {
if (arr[j] <= pivot) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
這兩個(gè)示例中,遞歸實(shí)現(xiàn)使用了函數(shù)調(diào)用棧來存儲(chǔ)待處理的子數(shù)組的邊界,而非遞歸實(shí)現(xiàn)使用了一個(gè)顯式的棧來達(dá)到相同的目的。在實(shí)際應(yīng)用中,選擇哪種實(shí)現(xiàn)方式取決于特定問題和需求。