JAVA 快速排序算法
时间: 2023-05-22 18:01:42 浏览: 58
Java 快速排序算法是一种基于分治思想的排序算法,它的时间复杂度为 O(nlogn)。它的基本思想是选择一个基准元素,将序列分成两部分,一部分比基准元素小,一部分比基准元素大,然后对这两部分分别进行递归排序。具体实现可以参考经典的快速排序算法实现。
相关问题
JAVA快速排序算法
快速排序是一种常用的排序算法,它的基本思想是通过一趟排序将待排序的数据分割成独立的两部分,其中一部分的所有数据都比另一部分的所有数据小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
下面是JAVA实现快速排序算法的示例代码:
```java
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high); // 划分数组
quickSort(arr, low, pivot - 1); // 对左子数组进行快速排序
quickSort(arr, pivot + 1, high); // 对右子数组进行快速排序
}
}
public 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; // 返回基准值的位置
}
public static void main(String[] args) {
int[] arr = {5, 2, 8, 9, 1, 3};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
以上代码实现了快速排序算法,通过递归调用`quickSort`函数对数组进行划分和排序,`partition`函数用于划分数组并返回基准值的位置。最后在`main`函数中调用`quickSort`函数对数组进行排序,并输出排序结果。
java 快速排序算法
快速排序算法是一种常用的排序算法,它的基本思想是通过划分将待排序的序列分成独立的两部分,其中一部分的所有元素都比另一部分小,然后再分别对这两部分进行排序,最终使整个序列有序。
下面是Java实现快速排序算法的示例代码:
```java
public class QuickSort {
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];
int i = low;
int j = high;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
if (i < j) {
arr[i++] = arr[j];
}
while (i < j && arr[i] <= pivot) {
i++;
}
if (i < j) {
arr[j--] = arr[i];
}
}
arr[i] = pivot;
return i;
}
public static void main(String[] args) {
int[] arr = {5, 2, 9, 3, 6, 1};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
输出结果为:1 2 3 5 6 9
希望以上代码能帮助到你!如果有任何问题,请随时提问。