JAVA-快速排序及对数器
快速排序
代码为:
package lianxi;
import java.util.Arrays;
import java.util.Random;
public class forDemo {
public static void main(String[] args) {
int[] arr = {1,3,4,9,7,10,2,5,6};
sort(arr,0,arr.length-1);
print(arr);
check();
}
public static void sort(int[] arr,int leftBound,int rightBound) {
//递归
if(leftBound>=rightBound) return;
int mid = partition(arr,leftBound,rightBound);
sort(arr,leftBound,mid-1);
sort(arr,mid+1,rightBound);
}
public static int partition(int[] arr,int leftBound,int rightBound) {
//排序
int pivot = arr[rightBound];
int left = leftBound;
int right = rightBound-1;
while(left<=right) {
while(left<=right&&arr[left]<=pivot) {
left++;
}
while(left<=right&&arr[right]>pivot) {
right--;
}
if(left<right) swap(arr,left,right);
}
swap(arr,left,rightBound);
return left;
}
static void swap(int[] arr,int i ,int j) {
//换位
int temp = arr[i];
arr[i]= arr[j];
arr[j] = temp;
}
static void print(int[] arr) {
//打印数组
for(int i = 0;i<arr.length;i++) {
System.out.print(arr[i] + " ");
}
}
static int[] generateRandom() {
//产生随机数组
Random r = new Random();
int[] arr = new int[100];
for(int i=0;i<arr.length;i++) {
arr[i] = r.nextInt(100);
}
return arr;
}
static void check() {
//对数器
int[] arr1 = generateRandom();
int[] arr2 =new int[arr1.length];
System.arraycopy(arr1, 0, arr2, 0, arr1.length);
Arrays.sort(arr1);
sort(arr2,0,arr2.length-1);
boolean same = true;
for(int i = 0;i<arr1.length;i++) {
if(arr1[i]!=arr2[i]) {
same = false;
}
}
System.out.println(same);
}
}