写一个Java版本的快排
时间: 2023-02-23 19:07:33 浏览: 91
快排序的Java实现
4星 · 用户满意度95%
好的,这是一个Java版本的快速排序代码:
```
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] array = {4, 5, 1, 6, 2, 7, 3, 8};
quickSort(array, 0, array.length-1);
System.out.println(Arrays.toString(array));
}
public static void quickSort(int[] array, int left, int right) {
if (left < right) {
int pivotIndex = partition(array, left, right);
quickSort(array, left, pivotIndex-1);
quickSort(array, pivotIndex+1, right);
}
}
public static int partition(int[] array, int left, int right) {
int pivot = array[right];
int i = left-1;
for (int j = left; j < right; j++) {
if (array[j] <= pivot) {
i++;
swap(array, i, j);
}
}
swap(array, i+1, right);
return i+1;
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
```
阅读全文