该快速排序实现是否始终正确选择数组最后一个元素作为基准?
问题:判断该Java快速排序实现是否始终选择数组最后一个元素作为基准
给定以下Java实现的快速排序算法,要求始终选择最后一个元素作为基准(Pivot),请判断该实现是否符合要求?
public class lab3q3 { public static void main(String args[]) { int[] array = {8, 2, 5, 3, 9, 4, 7, 6, 1}; quickSort(array, 0, array.length - 1); for (int i : array) { System.out.print(i + " "); } } private static void quickSort(int[] array, int start, int end) { if (end <= start) return; // Base case int pivotIndex = partition(array, start, end); quickSort(array, start, pivotIndex - 1); quickSort(array, pivotIndex + 1, end); } private static int partition(int[] array, int start, int end) { int pivotValue = array[end]; // Choose the last element as the pivot int i = start - 1; for (int j = start; j <= end; j++) { if (array[j] <= pivotValue) { i++; int temp = array[i]; array[i] = array[j]; array[j] = temp; } } return i; } }
回答
是,这个实现确实始终以当前处理的子数组最后一个元素作为基准。
核心依据在于partition方法的第一行:
int pivotValue = array[end];
这里直接取了当前子数组的end位置元素(也就是子数组的最后一个元素)作为基准值,并且这个值在整个partition过程中固定不变——后续的交换操作只是调整其他元素的位置,基准值始终是初始选取的子数组最后一个元素的值。
另外,递归调用quickSort时,每次传入的start和end参数明确限定了当前要排序的子数组范围,因此每次执行partition时,都会选取该子数组的最后一个元素作为基准,完全符合要求。
内容的提问来源于stack exchange,提问作者Hassan Awan
相关产品推荐
相关产品推荐

