下面是使用Java实现快速排序的一种方法:
public class QuickSort {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);}}private 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;}private static void swap(int[] arr, int i, int j) {int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}public static void main(String[] args) {int[] arr = {7, 2, 9, 3, 5, 8};int n = arr.length;quickSort(arr, 0, n - 1);System.out.println("排序后的数组:");for (int num : arr) {System.out.print(num + " ");}}
}
这是一个使用经典的"最右元素作为基准点"的快速排序算法实现。在quickSort
方法中,我们首先选择一个基准点(这里选择最右边的元素),然后通过partition
方法将数组划分为两个子数组,并返回基准点的索引。然后,我们递归地对划分后的子数组进行快速排序,直到排序完成。
在partition
方法中,我们通过遍历数组,将小于基准点的数放到左边,大于基准点的数放到右边,最后将基准点放到正确的位置上。这里使用了双指针的思想,使用i
来记录小于基准点的元素的最后一个位置。
在swap
方法中,我们用于交换数组中两个元素的位置。
在main
方法中,我们测试了快速排序算法的实现。输出结果为排序后的数组。