温馨提示×

java数组快速排序怎么实现

小亿
87
2023-11-08 18:09:59
栏目: 编程语言

以下是一种实现快速排序算法的Java代码:

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 9, 1, 3, 7};
        quickSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    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);
        }
    }

    public 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;
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

快速排序算法的关键在于 partition() 方法。该方法选择一个基准元素(一般选择最后一个元素),然后将数组分为两部分,使得左边的元素都小于等于基准元素,右边的元素都大于基准元素。然后递归地对左右两部分进行排序。快速排序是一种原地排序算法,不需要额外的空间。

以上代码实现了快速排序算法,通过调用 quickSort() 方法来进行排序。首先选择一个基准元素,然后将数组分为两部分,然后递归地对左右两部分进行排序。partition() 方法用于将数组分割为两部分,并返回基准元素的位置。swap() 方法用于交换数组中的两个元素。最后打印排序后的数组。

0