package com.algorithms;
/**
*
* pseudocode
*
* patition(A, p, q)
* x <- A[p]
* i <- p;
* for j <- p + 1 to q
* do if A[j] <= x
* then i <- i + 1
* exchange A[i] <- A[j]
* exchange A[p] <- A[i]
* return i
*
* quickSort(A, p, q)
* if p < q
* then r <- patition(A, p, q);
* quickSort(A, p, r-1)
* quickSort(A, r+1,q)
*/
public class Qucksort {
public static void main(String[] args) {
int[] a = { 6, 10, 13, 5, 8, 3, 2, 11 };
display(a);
System.out.println("");
quickSort(a, 0, a.length - 1);
display(a);
}
static void quickSort(int[] a, int p, int q) {
if (p < q) {
int r = patition(a, p, q);
quickSort(a, p, r - 1);
quickSort(a, r + 1, q);
}
}
static int patition(int a[], int p, int q) {
int x = a[p];
int i = p;
for (int j = p + 1; j <= q; j++) {
if (a[j] <= x) {
i++;
swap(a, i, j);
}
}
swap(a, p, i);
return i;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void display(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
java 快速排序
最新推荐文章于 2013-03-13 12:24:24 发布