温馨提示×

java实现快速排序的方法是什么

小亿
82
2024-03-07 17:12:29
栏目: 编程语言

快速排序是一种常用的排序算法,其思想是通过选择一个基准值,将数组分为两部分,左边部分所有元素都小于基准值,右边部分所有元素都大于基准值,然后分别对左右两部分递归进行快速排序。下面是Java实现快速排序的方法:

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (arr == null || arr.length == 0) {
            return;
        }
        if (low >= high) {
            return;
        }

        // Choose the pivot element
        int middle = low + (high - low) / 2;
        int pivot = arr[middle];

        // Make left < pivot and right > pivot
        int i = low, j = high;
        while (i <= j) {
            while (arr[i] < pivot) {
                i++;
            }
            while (arr[j] > pivot) {
                j--;
            }
            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }

        // Recursively sort two sub-parts
        if (low < j) {
            quickSort(arr, low, j);
        }
        if (high > i) {
            quickSort(arr, i, high);
        }
    }

    public static void main(String[] args) {
        int[] arr = {6, 3, 8, 2, 9, 1};
        quickSort(arr, 0, arr.length - 1);
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

在上面的代码中,quickSort方法用于实现快速排序,其中low表示数组的起始位置,high表示数组的结束位置。在main方法中,我们定义一个数组arr,然后调用quickSort方法对该数组进行排序,最后输出排序后的数组。

0