java快速排序算法(使用哨兵实现)
本算法效率非常高!具体解释我已经在代码前面加了注释。具体原理也都写在里面了。
import java.util.Random;
public class Quick_Sort {
public static void quicksort(int[] arry){
if(arry.length == 0){
System.out.println("空数组排个屁????");
return;
}
int left = 0;
int right = arry.length-1;
q_s(arry,left,right);
}
public static void q_s(int[] arry,int left,int right){
if(left > right){
return;
}
int low = left;
int high = right;
int p = arry[left];
while(low < high){
while(arry[high]>=p && low<high){
high--;
}
while(arry[low]<=p && low<high){
low++;
}
if(low<high){
int cache = arry[low];
arry[low] = arry[high];
arry[high] = cache;
}
int cache = arry[low];
arry[low] = arry[left];
arry[left] = cache;
q_s(arry,left,low-1);
q_s(arry,high+1,right);
}
}
public static void DaYin(int num[]){
System.out.println("打印数组:-------------------------------------");
System.out.print("[");
for(int i=0;i<num.length;i++){
System.out.print(num[i]+" ");
}
System.out.println("]");
System.out.println("打印数组:-------------------------------------");
}
public static void main(String[] args) {
int[] arry = new int[500];
Random r = new Random();
for (int i = 0; i < arry.length; i++) {
arry[i] = r.nextInt(100);
}
DaYin(arry);
quicksort(arry);
DaYin(arry);
}
}
运行结果: