欢迎访问宙启技术站
智能推送

快速排序算法的实现和Java函数调用方式?

发布时间:2023-07-02 05:09:25

快速排序(quicksort)是一种常用的排序算法,它使用分治法(Divide and conquer)的思想来进行排序。快速排序的基本思想是:从待排序的数据序列中选择一个元素作为基准(pivot),将比基准小的元素放在基准的左边,将比基准大的元素放在基准的右边,然后对左右两个子序列分别进行递归排序,最终得到有序的序列。

下面是快速排序算法的基本实现:

public class QuickSort {
    public static void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int partitionIndex = partition(arr, left, right); // 获取基准元素的位置
            quickSort(arr, left, partitionIndex - 1);  // 对基准元素左边的子序列进行递归排序
            quickSort(arr, partitionIndex + 1, right); // 对基准元素右边的子序列进行递归排序
        }
    }

    private static int partition(int[] arr, int left, int right) {
        int pivot = arr[left]; // 选择      个元素作为基准元素
        int i = left; // i指向小于基准的序列尾部
        for (int j = left + 1; j <= right; j++) { // 从基准元素后面的元素开始遍历
            if (arr[j] < pivot) { // 如果当前元素小于基准元素
                i++;
                swap(arr, i, j); // 将当前元素放入小于基准的序列尾部
            }
        }
        swap(arr, left, i); // 将基准元素放入合适的位置
        return i;
    }

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

在使用以上代码时,可以通过调用quickSort方法来对一个整数数组进行快速排序,示例如下:

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 9, 1, 3};
        QuickSort.quickSort(arr, 0, arr.length - 1);
        for (int num : arr) {
            System.out.print(num + " ");
        }
        // 输出结果为:1 2 3 5 8 9
    }
}

在Java中,函数的调用方式是通过类名+方法名的形式,所以通过QuickSort.quickSort()来调用quickSort方法,quickSort方法的参数是待排序的数组以及数组的左右边界。

快速排序算法的时间复杂度为O(nlogn),其中n是待排序序列的长度。这使得快速排序成为一种高效的排序算法,广泛应用于各种编程语言中。