快速排序是一种高效的排序算法,使用分治法,将数组递归地分为两个部分,并根据枢轴元素排序。该算法的复杂度为:最好情况:O(n log n)最坏情况:O(n^2)平均情况:O(n log n)
Java 数组快速排序算法
快速排序是一种高效的排序算法,使用分治法对数组进行排序。
算法步骤:
1. 选择一个枢轴元素:
于枢轴元素的部分和大于枢轴元素的部分。2. 分区:
3. 递归排序子数组:
算法复杂度:
代码示例:
public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
sort(arr, low, pivot - 1);
sort(arr, pivot + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = pivot;
arr[high] = temp;
return i + 1;
}
}