package jianzhioffer;
import java.util.Arrays;
public class QuickSort {
// 一次排序
public static int partition(int data[], int start, int end) {
if (data.length <= 0 || start < 0 ) {
System.err.println("不合法");
}
int key = start;
int value = data[0];
while (start != end) {
if (key<end) {
if (value < data[end]) {
swap(data, key, end);
key = end;
} else {
end--;
}
} else {
if (value > data[start]) {
swap(data, start, key);
key = start;
} else {
start++;
}
}
}
return key;
}
//交换数组元素
public static void swap(int data[], int i, int j) {
data[i] ^= data[j];
data[j] = data[i] ^ data[j];
data[i] ^= data[j];
}
//递归排序左右子序列
public static void quickSort(int[] data, int start, int end) {
if (start == end) {
return;
}
int key = partition(data, start, end);
if(key<end)
quickSort(data, key+1, end);
if(key>start)
quickSort(data, start, key-1);
}
//测试
public static void main(String[] args) {
int[] data = new int[] { 2, 5, 1, 5, 7, 8 };
quickSort(data, 0, data.length - 1);
System.out.println(Arrays.toString(data));
}
}
快速排序java
最新推荐文章于 2023-06-04 10:54:50 发布