import java.util.Arrays;
/**
* QuickSort Class
*
* @author YangJinyang
* @date 2018/05/12
*/
public class QuickSortClass {
//测试
public static void main(String[] args){
int[] array = {1,2,3,5,6,9,8,4,7};
QuickSortClass qs = new QuickSortClass();
qs.quickSort(array,0,array.length - 1);
//输出数据
System.out.print(Arrays.toString(array));
}
public void quickSort(int[] array, int p, int r) {
if (p < r) {
int q = partition1(array, p, r);
quickSort(array, p, q - 1);
quickSort(array, q + 1, r);
}
}
/**
* 快速排序
* */
public int partition0(int[] array, int p, int r) {
//基准
int x = array[p];
int i = p;
int j = r;
int temp;
while (i != j) {
while (array[j] >= x && i < j){
j--;
}
while (array[i] <= x && i < j){
i++;
}
if(i < j){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
array[p] = array[i];
array[i] = x;
return i;
}
/**
* 快速排序(算法导论)
* */
public int partition1(int[] array, int p, int r){
int x = array[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (array[j] <= x) {
i++;
exchange(array,i,j);
}
}
exchange(array,r,i+1);
return i + 1;
}
/**
* 交换数组中a[i]和a[j]
* @param a
* @param i
* @param j
*/
public static void exchange(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}