java快速排序

来源:互联网 发布:软件源代码下载 编辑:程序博客网 时间:2024/06/04 18:53

本文是算法导论上面的快速排序的方法实现:

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]; // exchangea[i] = a[j];a[j] = temp;}}temp = a[i]; // exchangea[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;}}


0 0