本文是算法导论上面的快速排序的方法实现:
package sort;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class QuickSort {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
// 输入8个数字
StringTokenizer st = new StringTokenizer(f.readLine());
int a[] = new int[8];
for (int i = 0; i < 8; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
a = QuickS(a, 0, 7);
for (int i = 0; i < 8; i++) {
out.print(a[i] + " ");
}
out.close();
f.close();
}
// 将数组a[]中的两个部分合并排序为一个
static int partition(int a[], int p, int q) {
int x, i, j, temp;
x = a[p]; // 将最后一个值保存在x中
i = p; // 开始的时候将i 移动到数组的外面
for (j = p + 1; j <= q; j++) {
if (a[j] <= x) // 比较比x大的数,并交换位置
{
i += 1;
temp = a[i]; // exchange
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i]; // exchange
a[i] = a[p];
a[p] = temp;
return i;
}
// 递归的调用排序,并返回排序后的数组
static int[] QuickS(int a[], int first, int last) {
if (first < last) {
int r = partition(a, first, last);
QuickS(a, first, r - 1); // 左边有序
QuickS(a, r + 1, last); // 右边有序
}
return a;
}
}