有一个月没有写代码了,之前一直在忙着复习的事情,考试完了,学校还搞了一周的实训,没有时间来写。。。,寒假回家准备重温一下数据结构的知识,为以后的刷算法题做准备。
public class QuickSort {
public static void main(String [] args){
Integer [] test = new Integer[15];
for(int i=0;i<test.length;i++){
test[i] = (int)(Math.random() * 100);
}
System.out.println("the arriy is :");
show(test);
StdRandom.shuffle(test);
System.out.println("After being shufferef the arriy is :");
show(test);
sort(test,0,test.length-1);
System.out.println("After being sorted the arriy is :");
show(test);
}
/*
用来交换数组索引位置为i和j的值
*/
public static void exec(Comparable [] a,int i,int j){
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
/*
用来比较数组中2个数的大小
*/
public static boolean less(Comparable a,Comparable b){
return a.compareTo(b) < 0 ? true:false;
}
//将数组划分成2部分在最后的返回值j之前的小于a[j],后面的大于a[j]
private static int partication(Comparable [] a,int lo,int hi){
int i = lo;
int j = hi + 1;
Comparable V = a[lo];
while (true){
while(less(a[++i],V)) {
if (i == hi) break;
}
while(less(V,a[--j])){
if(j==lo) break;
}
if(i>=j)break;
exec(a,i,j);
}
exec(a,lo,j);
return j;
}
//用分治法来进行快速排序
public static void sort(Comparable [] a,int lo,int hi){
if(lo >= hi) return;
int j = partication(a,lo,hi);
sort(a,lo,j-1);
sort(a,j+1,hi);
}
public static void show(Comparable [] a){
for(Comparable i:a){
System.out.print(i+" ");
}
System.out.println();
}
}