突然兴致起,想想写写一下排序的算法,这当然要写这个nlog(n)时间级别的快速排序了。
直接贴代码。就是复习一下。
public class FastSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] num = {23,24,12,45,67,26,41,32,19,16,37,29};
num = quick(num);
StringBuilder output = new StringBuilder();
for(int i =0;i<num.length;i++){
output.append(num[i]);
output.append(",");
}
System.out.print(output.substring(0, output.length()-1));
//顺便把StringBuilder类介绍一下,这个类与string类不一样,它是可以动态改变的。
}
private static int[] quick(int[] a) {
if(a.length > 0){ //判断是否小于0
a = quicksort(a , 0, a.length -1);
}
return a;
}
private static int[] quicksort(int[] a, int low, int hight) {
if(low < hight){
int middle = getMiddle(a , low ,hight);
quicksort(a,low,middle-1);
quicksort(a,middle +1,hight);
}
return a;
}
private static int getMiddle(int[] a, int low, int hight) {
int temp = a[low]; //做一个哨兵的作用,其实就是第一个取得的中间值
while(low < hight){
while(low < hight && a[hight] >= temp )
hight --;
a[low] = a[hight];//把高位的小于哨兵的置换到低位去
while(low < hight && a[low] <= temp)
low ++;
a[hight] = a[low];
}
a[low] = temp;
return low;
//所以这里是先换了一个高位的,再换一个低位的,如此折腾到最后
}
}