在Java中實現快速排序算法時,可以使用以下參數設置作為建議:
以下是一個簡單的Java快速排序實現示例:
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
int n = arr.length;
quickSort(arr, 0, n - 1);
System.out.println("Sorted array: ");
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
static void quickSort(int[] arr, int low, int high) {
if (low< high) {
int pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1); // Before pivotIndex
quickSort(arr, pivotIndex + 1, high); // After pivotIndex
}
}
static int partition(int[] arr, int low, int high) {
int pivot = arr[high]; // Select last element as pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j< high; j++) {
if (arr[j] <= pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
}
這個示例中,我們使用了最后一個元素作為基準值,并對數組進行原地排序。你可以根據實際需求調整基準值的選取方法和排序策略。