温馨提示×

Java快速排序的实际案例分析

小樊
82
2024-09-09 18:37:34
栏目: 编程语言

快速排序(Quick Sort)是一种高效的排序算法,其基本思想是通过选取一个基准元素,将数组分为两部分,使得一部分的元素都小于基准元素,另一部分的元素都大于基准元素,然后对这两部分分别进行快速排序

下面是一个Java实现的快速排序示例:

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {3, 7, 8, 5, 2, 1, 9, 5, 4};
        quickSort(arr, 0, arr.length - 1);
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    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[low];
        while (low< high) {
            while (low< high && arr[high] >= pivot) {
                high--;
            }
            arr[low] = arr[high];
            while (low< high && arr[low] <= pivot) {
                low++;
            }
            arr[high] = arr[low];
        }
        arr[low] = pivot;
        return low;
    }
}

在这个示例中,我们首先定义了一个名为quickSort的方法,该方法接受一个整数数组、一个低索引和一个高索引作为参数。我们在main方法中创建了一个整数数组,并调用quickSort方法对其进行排序。排序完成后,我们遍历并打印排序后的数组。

partition方法是快速排序的核心部分,它负责将数组划分为两部分。我们首先选择一个基准元素(本例中为数组的第一个元素),然后从数组的两端开始遍历。当遇到一个小于基准元素的值时,我们将其与高索引处的值交换;当遇到一个大于基准元素的值时,我们将其与低索引处的值交换。最后,我们将基准元素放到正确的位置上,并返回其索引。

通过递归地对基准元素左右两侧的子数组进行快速排序,我们可以实现整个数组的排序。在这个示例中,我们得到的排序结果为:1 2 3 4 5 5 7 8 9。

0