用java生成一个快速排序
时间: 2023-05-22 11:06:28 浏览: 44
的实现代码。
可以的,下面是一个用 Java 实现的快速排序的示例代码:
```java
import java.util.*;
public class QuickSort {
public static void main(String[] args) {
int[] arr = {4, 6, 1, 3, 8, 5, 7, 2};
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
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);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[left];
int i = left + 1;
int j = right;
while (i <= j) {
while (i <= j && arr[i] < pivot) {
i++;
}
while (i <= j && arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
int pivotIndex = j;
arr[left] = arr[pivotIndex];
arr[pivotIndex] = pivot;
return pivotIndex;
}
}
```
这段代码可以对一个 int 数组进行快速排序,算法的时间复杂度为 O(n log n)。