package com.cisco.www.test;
/**
* 快排
*/
public class QuickSort1 {
public static void quickSort(int[] arr){
if(arr==null||arr.length<2){
return;
}
quickSort(arr,0,arr.length-1);
}
//随机快排
private static void quickSort(int[] arr, int l, int r) {
if (l < r) {
//将数组中随机位置上的元素和最后位置上的元素进行交换
swap(arr, l + (int) (Math.random() * (r - l + 1)), r);
int[] p = partition(arr, l, r);
quickSort(arr, 0, p[0] - 1);
quickSort(arr, p[1] + 1, r);
}
}
//
public static int[] partition(int[] arr, int l, int r) {
int less = l-1;
int more = r;
while (l<more){
if(arr[l]<arr[r]){
swap(arr,++less,l++);
}
if(arr[l]>arr[r]){
swap(arr,l,--more);
}else {
l++;
}
}
swap(arr,more,r);
return new int[]{less+1,more};
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//test
public static void main(String[] args){
int testTime =1000000;
int size =100;
int value =100;
boolean succeed =true;
for(int i =0 ; i<testTime;i++){
int[] arr1 = generateRandomArray(size,value);
int[] arr2 = copyArray(arr1);
if(!isEqual(arr1,arr2)){
succeed=false;
break;
}
}
System.out.println(succeed?"Nice":"Fuck Fucked!");
int[] arr = generateRandomArray(size,value);
printArray(arr);
quickSort(arr);
printArray(arr);
}
private static void printArray(int[] arr) {
if(arr==null){
return;
}
for(int i = 0 ; i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
//test
public static boolean isEqual(int[] arr1, int[] arr2) {
if((arr1!=null&&arr2==null)||(arr1==null&&arr2!=null)){
return false;
}
if(arr1==null&&arr2==null){
return true;
}
if(arr1.length!=arr2.length){
return false;
}
for(int i = 0 ; i <arr1.length;i++){
if(arr1[i]!=arr2[i]){
return false;
}
}
return true;
}
//test
public static int[] generateRandomArray(int size ,int value){
int[] arr = new int[(int)(Math.random()*(size+1))];
for(int i = 0 ; i<arr.length;i++){
arr[i] = (int)(Math.random()*(size+1)) - (int)(Math.random()*(size));
}
return arr;
}
//test
public static int[] copyArray(int[] arr){
if(arr==null){
return null;
}
int[] res = new int[arr.length];
for(int i = 0 ; i <arr.length;i++){
res[i] = arr[i];
}
return res;
}
}