Java 快速排序:理解核心概念和实现242


快速排序是一种高效的排序算法,以其时间复杂度 O(n log n) 和出色的平均性能而闻名。它是一种分而治之算法,将数组划分为较小的子数组,递归地对每个子数组进行排序,然后合并已排序的子数组以获得最终的排序数组。

快速排序的伪代码如下:
```
quickSort(arr[], low, high)
if low < high
pi = partition(arr[], low, high)
quickSort(arr[], low, pi - 1)
quickSort(arr[], pi + 1, high)
```

其中,partition 函数负责将数组划分为较小的子数组。它选择一个枢轴元件,然后将比枢轴元件小的元素移动到枢轴元件的左边,而将比枢轴元件大的元素移动到枢轴元件的右边。枢轴元件将子数组划分为左右两个较小的子数组。

以下 Java 代码实现了快速排序算法:```java
public class QuickSort {
public static void main(String[] args) {
int[] arr = { 10, 7, 8, 9, 1, 5 };
quickSort(arr, 0, - 1);
("Sorted array:");
for (int i : arr) {
(i + " ");
}
}
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// Partition the array around the pivot element
int pi = partition(arr, low, high);
// Recursively sort the left and right subarrays
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
public static int partition(int[] arr, int low, int high) {
// Choose a pivot element
int pivot = arr[high];
// Initialize the index of the smaller element
int i = (low - 1);
// Loop through the array and arrange elements around the pivot
for (int j = low; j

2024-10-18


上一篇:Java泛型中的泛型方法

下一篇:Java 方法反射:深入探索