快速排序法又叫二分法排序:
import java.util.Random;
public class Quicksort {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr =new int[100];
Random rand=new Random();
for (int i = 0; i < arr.length; i++) {
arr[i]=rand.nextInt(500); //定义 [0,500)之内的随机数
}
quickSort(arr, 0, arr.length-1);
for(int i = 0;i<arr.length;i++){
if (i==0) {
System.out.print("快速排序 圣墟: [ "+arr[i]+",");
}else if (i==arr.length-1) {
System.out.print(arr[i]+" ]");
System.out.println();
}else {
System.out.print(arr[i]+",");
}
}
}
public static void quickSort(int[] arr,int low,int high){
int i,j,temp,t;
if(low>high){
return;
}
i=low;
j=high;
//temp就是基准位
temp = arr[low];
while (i<j) {
//先看右边,依次往左递减
while (temp>=arr[j]&&i<j) {
j--;
}
//再看左边,依次往右递增
while (temp<=arr[i]&&i<j) {
i++;
}
//如果满足条件则交换
if (i<j) {
t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
//最后将基准为与i和j相等位置的数字交换
arr[low] = arr[i];
arr[i] = temp;
//递归调用左半数组
quickSort(arr, low, j-1);
//递归调用右半数组
quickSort(arr, j+1, high);
}
}