public class QuickSortTest {
public static void main(String[] args) {
int[] arr = new int[50];
int[] arr2 = new int[50];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random() * 200);
arr2[i] = arr[i];
}
//遍历打印
System.out.println("排序前的数组 arr");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("排序前的数组 arr2");
for (int i : arr2) {
System.out.print(i + " ");
}
System.out.println();
QuickSortTest test = new QuickSortTest();
test.qucikSort(arr,0,arr.length-1);
System.out.println("排序后的数组arr");
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
//对比工具类排序:
System.out.println("对比工具类排序 arr2");
Arrays.sort(arr2);
for (int i : arr2) {
System.out.print(i + " ");
}
}
public void qucikSort(int[] arr,int low ,int high){
if(low > high){
return;
}
int temp;
int i = low;
int j = high;
int jzz = arr[low];
while(i < j){
//循环结束时找到本次的第一个比基准值小的值
while(jzz <= arr[j] && i < j){
j--;
}
//循环结束时找到本次的第一个比基准值大的值
while(jzz >= arr[i] && i < j){
i++;
}
//交换二者的值
if(i < j){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
//i = j时,与 基准值 交换此时的值
arr[low] = arr[j];
arr[j] = jzz;
//递归
qucikSort( arr, j+1 , high);
qucikSort( arr, low , j-1);
}
}