![](https://csdnimg.cn/release/download_crawler_static/89342738/bg1.jpg)
以下是使用 Java 编写的快速排序(Quick Sort)算法的实现:
java 复制代码
public class QuickSort {
// 快速排序算法实现
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
// 划分操作
int pivotIndex = partition(arr, left, right);
// 递归地对左右两部分进行排序
quickSort(arr, left, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, right);
}
}
// 划分操作
private static int partition(int[] arr, int left, int right) {
// 选择最右边的元素作为基准值
int pivot = arr[right];
int i = left - 1; // 指向小于基准值的元素的索引
for (int j = left; j <= right - 1; j++) {
// 如果当前元素小于或等于基准值
if (arr[j] <= pivot) {
// 增加 i
i++;
// 交换 arr[i]和 arr[j]
swap(arr, i, j);
}
}
// 将基准值放到正确的位置
swap(arr, i + 1, right);
return i + 1;
}
// 交换数组中两个元素的位置