package com.mianshi;
/**
* describe: 快速排序算法2(排序結果從小到大)
* create on: 2011-05-25
* @author sylor.liu
* @version 1.0
* @since jdk1.6
*/
public class QuickSort2 {
private void swap(int a[], int x, int y){
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
// 對數據進行快速排序
private void qsort(int a[], int low,int high){
// 將該段數據的第一個值a[low]設爲基準值
int point = a[low];
int left = low + 1;
int right = high;
if(low == high){
return;
}
if(high - low ==1 ){
if(a[high] < a[low]){
swap(a,high,low);
}
return;
}
// 將該段數據的值進行互換,使左邊的值小於point 右邊的值大於point 且a[left-1]從左邊起第一個大於point值
while(left < right){
while(left < right&& left < high){
if(a[left] > point){
break;
}
left++;
}
while(left < right&& right > low){
if(a[right] < point){
break;
}
right--;
}
swap(a,left,right);
}
// 左邊起第一個大於point值a[left-1] 與a[low]互換
swap(a,low,left-1);
// 對左半段排序
qsort(a,low,left-1);
// 對右半段排序
qsort(a,left ,high);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = new int[]{12,2,9,5,67,32,6,7,33};
QuickSort2 qs = new QuickSort2();
qs.qsort(a,0,a.length - 1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ;");
}
System.out.println();
}
}