import java.util.Date;
public class Test21 {
//交换数据
public static void swap(int[] arr,int i,int j){
if(i!=j){
arr[i]=arr[i]^arr[j];
arr[j]=arr[i]^arr[j];
arr[i]=arr[i]^arr[j];
}
}
public static void InsertSort(int[] arr){
if(arr==null){
return;
}
for (int i = 1; i < arr.length; i++) {
for (int j = i-1; j >=0 &&arr[j]>arr[j+1]; j--) {
swap(arr,j,j+1);
}
}
}
//要使用递归 ,因此 要传 '真实数组'
public static void mergeSort(int[] arr,int L,int R){
if(L==R){
return;
}
//int mid=L+((R-L)>>1);
int mid=(L+R)/2;
mergeSort(arr,L,mid);
mergeSort(arr,mid+1,R);
merge(arr,L,mid,R);
}
public static void merge(int[] arr,int L ,int mid,int R){
int n=R-L+1;
int[] help=new int[n];
int i=0;
int p1=L;
int p2=mid+1;
while(p1<=mid&&p2<=R){
//左右边那个大就把那个给help数组
help[i++]=arr[p1]<arr[p2]?arr[p1++]:arr[p2++];
}
// 越界
while(p1<=mid){
help[i++]=arr[p1++];
}
while(p2<=R){
help[i++]=arr[p2++];
}
//最后要把help数组 拷贝回 arr数组
for (int j = 0; j < n; j++) {
//往 arr拷贝 要从 此时arr数组的 左边界开始
arr[L+j]=help[j];
}
}
public static void print(int[] arr){
if(arr==null){
return;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
public static void insetSort(){
}
//对数器
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()*(value+1))-(int)(Math.random()*value));
}
return arr;
}
//
public static int[] copyArray(int[] arr){
if (arr==null){
return null;
}
int[] help=new int[arr.length];
for (int i = 0; i < help.length; i++) {
help[i]=arr[i];
}
return help;
}
public static void main(String[] args) {
int[] arr = generateRandomArray(100000, 168);
int[] arr1=copyArray(arr);
print(arr);
System.out.println();
print(arr1);
System.out.println("\n--------------------\n");
long time1 = new Date().getTime();
mergeSort(arr,0,arr.length-1);
long time2 = new Date().getTime();
System.out.println("\n--------------------\n");
System.out.println("时间1为:"+(time2-time1));
print(arr);
System.out.println("\n--------------------\n");
Date date3=new Date();
long time3 = date3.getTime();
InsertSort(arr1);
Date date4=new Date();
long time4 = date4.getTime();
System.out.println("\n--------------------\n");
System.out.println("时间为2为:"+(time4-time3));
print(arr1);
}
}