在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;
}
}
这个示例中,我们使用了最后一个元素作为基准值,并对数组进行原地排序。你可以根据实际需求调整基准值的选取方法和排序策略。