java 排序方式(二)
快速排序
public static void kuaisu_sort(int[] arry,int first,int last) {
if(last > first) {
int pivotIndex = kuaisu_sortvoid(arry,first,last);
kuaisu_sort(arry,first,pivotIndex-1);//前半部分
kuaisu_sort(arry,pivotIndex+1,last);//后半部分
}
}
public static int kuaisu_sortvoid(int[] arry,int first,int last) {
int privot = arry[first];
int low = first + 1;
int high = last;
while(low < high) {
/**
* 从前向后和从后向前依次和主元比较,当前面的元素比主元大,后面的元素比主元小则这两个元素互换位置
*/
while(low <= high && arry[low] <= privot) {
low++;
}
while(low <= high && arry[high] >= privot) {
high--;
}
if(high > low) {
int temp = arry[high];
arry[high] = arry[low];
arry[low] = temp;
}
}
while(high > first && arry[high] >= privot) {
high--;
}
if(privot > arry[high]) {
arry[first] = arry[high];
arry[high] = privot;
return high;
}else {
return first;
}
}
public static void main(String[] args) {
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
kuaisu_sort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
}