快速排序:
package com.it.test;
//快速排序
public class _02kuaipai {
public static int partition(int[] a, int low, int high) {
int base = a[low];
while (low < high) {
while (low < high && a[high] > base) {
high--;
}
a[low] = a[high];
while (low < high && a[low] <= base) {
low++;
}
a[high] = a[low];
}
a[low] = base;
return low;
}
public static void sort(int[] a, int low, int high) {
if (low < high) {
int index = partition(a, low, high);
sort(a, low, index);
sort(a, index + 1, high);
}
}
public static void print(int[] a, int low, int high) {
for (int i = 0; i < low; i++) {
System.out.print("\t");
}
for (int i = low; i <= high; i++) {
System.out.print(a[i] + "\t");
}
System.out.println();
}
public static void main(String[] args) {
int[] a = { 1, 4, 6, 2, 0, 3, 5, 8, 10 ,7 , 9};
System.out.print("排序前:\t");
print(a, 0, a.length - 1);
sort(a, 0, a.length - 1);
System.out.print("排序后:\t");
print(a, 0, a.length - 1);
}
}
运行结果: