package com.sksort;
public class exchange_Quick {
public static void main(String[] args) {
int a[] = {10,9,8,7,6,5,4,3,2,1};
exchange_Quick q = new exchange_Quick();
q.sort(a, 0, a.length-1);
q.show(a);
}
public void sort(int a[],int low,int high){
int middle;
//if(low < high)
while(low < high){
//首先找到中间点
middle = exchange(a,low,high);
//中间点左边的递归找到中间点
sort(a,low,middle-1);
//中间点右边的递归找到中间点
//sort(a,middle+1,high);
/**
* 当我们把if改成while后,因为第一次递归以后,变量low就没有用处了
* 所以可以讲middle+1赋值给low,再循环的时候,来一次exchange
* 跟sort(a,middle+1,high);的效果是一样的
*/
low = middle + 1;//采用迭代而非递归的方式可以缩短堆的深浅
}
}
int exchange(int a[],int low,int high){
int temp;
//改进1,随机抽取三个数,排序,取中间大的那个数放在low处
int index;
index = low + (high-low)/2;
if(a[low]>a[high]){//交换左端与右端数据,保证左端较小
temp = a[low];
a[low] = a[high];
a[high] = temp;
}
if(a[index]>a[high]){//交换中间与右端数据,保证中间较小
temp = a[index];
a[index] = a[high];
a[high] = temp;
}
if(a[low]<a[index]){//交换左端与中间的数据,保证左端较大
temp = a[low];
a[low] = a[index];
a[index] = temp;
}else{}
//******************************************************/
temp = a[low];
while(low < high){
while((low < high)&&(a[high]>temp))
--high;
a[low] = a[high];//此处用替换代替交换,减少不必要的交换
while((low<high)&&(a[low]<temp))
++low;
a[high] = a[low];
}
a[low] = temp;
return low;
}
public void show(int a[]) {
for (int i = 0; i < a.length; i++) {
if (i == 0)
System.out.print(a[i]);
else
System.out.print(" " + a[i]);
}
System.out.println();
}
}