public class JQuickSort {
public static void main(String[] argv) {
// JQuickSort qs = new JQuickSort(Integer.parseInt(argv[0]));
JQuickSort qs = new JQuickSort(20);
qs.start();
}
int[] a = null;
public JQuickSort(int num) {
a = new int[num];
for (int i = 0; i < num; ++i) {
int n = (int) (Math.random() * 9999);
a[i] = n;
}
}
int partition(int number[], int left, int right) {
int i, j, s;
s = number[right];
i = left - 1;
for (j = left; j < right; j++) {
if (number[j] <= s) {
i++;
int tmp = number[i];
number[i] = number[j];
number[j] = tmp;
}
}
int tmp = number[i + 1];
number[i + 1] = number[right];
number[right] = tmp;
return i + 1;
}
private void printArray() {
System.out.print("Array: ");
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i] + " ");
}
System.out.println();
}
void quicksort(int number[], int left, int right) {
int q;
if (left < right) {
q = partition(number, left, right);
quicksort(number, left, q - 1);
quicksort(number, q + 1, right);
}
}
private void start() {
printArray();
quicksort(a, 0, a.length - 1);
printArray();
}
}
|
沒有留言:
張貼留言