import java.util.Random;
/**
*/
public class QuickSort {
private int[] array;
public QuickSort(int[] array) {
this.array = array;
}
private boolean checkResult() {
if (array.length == 1) {
return true;
} else {
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
return false;
}
}
}
return true;
}
private void display() {
for (int key : array) {
System.out.print(key + " ");
}
System.out.println();
}
private void quickSort(int start, int end) {
if (start < end) {
int flag = partition(start, end);
quickSort(start, flag - 1);
quickSort(flag + 1, end);
}
}
private int partition(int start, int end) {
int flag = start + new Random().nextInt(end - start);
exchangeElement(start, flag);
int key = array[start];
while (start < end) {
while (array[end] >= key && start < end) {
end--;
}
if (start < end) {
array[start] = array[end];
start++;
}
while (array[start] <= key && start < end) {
start++;
}
if (start < end) {
array[end] = array[start];
end--;
}
}
array[start] = key;
// display();
return start;
}
private void exchangeElement(int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 1000; i++) {
int[] array = new int[100];
for (int j = 0; j < 100; j++) {
array[j] = random.nextInt(30);
}
QuickSort quickSort = new QuickSort(array);
quickSort.quickSort(0, array.length - 1);
if (!quickSort.checkResult()) {
System.err.println("wrong!");
quickSort.display();
} else {
System.out.println("yes");
quickSort.display();
}
}
}
}
快速排序java版实现
最新推荐文章于 2024-03-10 10:07:00 发布