固原建站公司,厦门市住房和城乡建设局网站,如何做免费网站,太原首页推广下面是使用Java实现快速排序的一种方法#xff1a;
public class QuickSort {public static void quickSort(int[] arr, int low, int high) {if (low high) {// 将数组划分为两个子数组#xff0c;并获取划分点的索引int pivotIndex partition(arr, low, high);// 递…下面是使用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方法中我们测试了快速排序算法的实现。输出结果为排序后的数组。