java的快速排序怎么写?
时间: 2023-09-04 10:03:59 浏览: 79
### 回答1:
Java的快速排序实现方法如下:
```
public class QuickSort {
public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
quickSort(arr, 0, arr.length-1);
System.out.println("排序后的数组:");
for (int i : arr) {
System.out.print(i + " ");
}
}
private static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// 指定基准数
int middle = low + (high - low) / 2;
int pivot = arr[middle];
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
}
```
### 回答2:
快速排序是一种常用的排序算法,它基于分治的思想。下面是用Java实现快速排序的方法:
1. 选择一个基准元素,通常是待排序序列的第一个元素。
2. 将待排序序列分成两部分,小于基准元素的部分和大于基准元素的部分。
3. 对两个部分分别进行快速排序,递归地调用步骤1和步骤2,直到每个部分只剩一个元素或没有元素。
4. 将两个有序的部分合并起来,即得到最终的有序序列。
下面是快速排序的Java代码实现:
```
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int index = partition(arr, low, high);
quickSort(arr, low, index - 1);
quickSort(arr, index + 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 = {8, 3, 1, 5, 7, 2, 4, 6};
quickSort(arr, 0, arr.length - 1);
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
以上代码实现了快速排序算法。首先定义了`quickSort()`方法来实现递归排序,然后定义了`partition()`方法来进行元素分区。最后在`main()`方法中调用`quickSort()`方法,并输出排序结果。
这段代码的时间复杂度为O(nlogn),平均情况下具有较好的性能。
### 回答3:
快速排序是一种常用的排序算法,通过分治法实现。其基本思想是将数组分成两部分,一部分小于基准值,一部分大于基准值,然后对这两部分分别进行快速排序,以达到整个数组有序的目的。
具体的快速排序的实现步骤如下:
1. 选择一个基准值。可以选择数组的第一个元素作为基准值。
2. 定义两个指针,一个指向数组的起始位置,一个指向数组的终止位置。
3. 将数组分成两部分,小于基准值的元素放在左边,大于基准值的元素放在右边,将基准值放在分界点的位置。
4. 分别对左边和右边的子数组进行快速排序。递归调用快速排序函数。
5. 合并两个子数组,得到有序的数组。
具体的快速排序的Java代码如下:
```java
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int index = partition(arr, low, high);
quickSort(arr, low, index - 1);
quickSort(arr, index + 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;
}
}
```
使用该代码可以对一个整数数组进行快速排序。
快速排序的时间复杂度为O(nlogn),其中n为数组的大小。