溫馨提示×

java實現(xiàn)快速排序的方法是什么

小億
82
2024-03-07 17:12:29
欄目: 編程語言

快速排序是一種常用的排序算法,其思想是通過選擇一個基準值,將數(shù)組分為兩部分,左邊部分所有元素都小于基準值,右邊部分所有元素都大于基準值,然后分別對左右兩部分遞歸進行快速排序。下面是Java實現(xiàn)快速排序的方法:

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方法用于實現(xiàn)快速排序,其中low表示數(shù)組的起始位置,high表示數(shù)組的結(jié)束位置。在main方法中,我們定義一個數(shù)組arr,然后調(diào)用quickSort方法對該數(shù)組進行排序,最后輸出排序后的數(shù)組。

0