package test; import java.util.Date; public class InsertSort { public static void main(String args[]){ System.out.println(new Date()); int []array=new int[100000]; int []array1=new int[100000]; int []array2=new int[100000]; int []array3=new int[100000]; int []array4=new int[100000]; int []arrtemp=new int[]{13,2,44,23,12,13,25,98,8}; int delta[]=new int[]{10,5,3,1}; for(int i=99999;i>=0;i--){ array[i]=(int)(Math.random()*100000); } array1=array.clone(); array2=array.clone(); array3=array.clone(); array4=array.clone(); int arr[]=directInsertSort(array); int arr1[]=binInsertSort(array1); int arr2[]=shellSort(array2,delta); int arr3[]=bubbleSort(array3); long start=new Date().getTime(); quickSort(array4,0,array4.length-1); long end=new Date().getTime(); System.out.println("快速排序"+(end-start)); System.out.println(new Date()); /** for(int value:arrtemp) System.out.print(" "+value+" "); System.out.println(""); for(int value:arr2) System.out.print(" "+value+" "); System.out.println(""); for(int value:arr3) System.out.print(" "+value+" "); for(int i=100000;i>=99990;i--){ System.out.print(" "+arr1[i-1]+" "); } System.out.println(""); for(int i=100000;i>=99990;i--){ System.out.print(" "+arr2[i-1]+" "); } */ } public static int[] directInsertSort(int []arr){ long start=new Date().getTime(); for(int i=0;i<arr.length;i++){ int temp=arr[i]; for(int j=i-1;j>=0;j--){ if(temp<arr[j]){ arr[j+1]=arr[j]; arr[j]=temp; } } } long end=new Date().getTime(); System.out.println("直接插入排序"+(end-start)); return arr; } public static int[] binInsertSort(int arr[]){ long start=new Date().getTime(); for(int i=0;i<arr.length;i++){ int temp=arr[i]; int lo=0; int hi=i; while(lo<=hi){ int mid=(hi+lo)/2; if(arr[mid]<arr[i]) lo=mid+1; else hi=mid-1; } for(int j=i-1;j>hi;j--) arr[j+1]=arr[j]; arr[hi+1]=temp; } long end=new Date().getTime(); System.out.println("折半插入排序"+(end-start)); return arr; } public static int[] shellSort(int arr[],int delta[]){ //delta为步长 long start=new Date().getTime(); for(int i=0;i<delta.length;i++){ int delta1=delta[i]; for(int j=delta1;j<arr.length;j++){ if(arr[j]<arr[j-delta1]){ int temp=arr[j]; int k=j-delta1; for(;k>=0&&temp<arr[k];k=k-delta1){ arr[k+delta1]=arr[k]; } arr[k+delta1]=temp; } } } long end=new Date().getTime(); System.out.println("希尔排序"+(end-start)); return arr; } public static int[] bubbleSort(int arr[]){ long start=new Date().getTime(); for(int i=0;i<arr.length;i++){ for(int j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ int temp=arr[j+1]; arr[j+1]=arr[j]; arr[j]=temp; } } } long end=new Date().getTime(); System.out.println("冒泡排序"+(end-start)); return arr; } public static void quickSort(int arr[],int left,int right){ if(left<right){ int pivot=arr[left]; int low=left; int high=right; while(low<high){ while(low<high&&arr[high]>=pivot) high--;
arr[low]=arr[high]; while(low<high&&arr[low]<=pivot) low++; arr[high]=arr[low]; } arr[low]=pivot; quickSort(arr,left,low-1); quickSort(arr,low+1,right); } } }