BinaryInsertion
<Introduction to algorithm>
Observe that the while loop of lines 5–7 of the INSERTION-SORT procedure in
Section 2.1 uses a linear search to scan (backward) through the sorted subarray
AOE1 : : j 1. Can we use a binary search (see Exercise 2.3-5) instead to improve
the overall worst-case running time of insertion sort to ‚.n lg n/?
1 public class BinaryInsertion { 2 3 public static int binarySearch(int[] input,int target,int from,int to){ 4 int range=to-from; 5 if(range>0){ 6 int mid = (from+to)/2; 7 if(input[mid]>target){ 8 return binarySearch(input,target,from,mid-1); 9 } 10 else{ 11 return binarySearch(input, target, mid+1, to); 12 } 13 } 14 else{ 15 if(input[from] > target){ 16 return from; 17 } 18 else{ 19 return from+1; 20 } 21 } 22 } 23 24 public static void sort(int[] a){ 25 for(int j = 1; j < a.length; j++){ 26 int key = a[j]; 27 int index=binarySearch(a, a[j], 0, j-1); 28 for(int i=j;i>index;i--){ 29 a[i]=a[i-1]; 30 } 31 a[index]=key; 32 } 33 } 34 public static void printArray(int[] a){ 35 for(int i = 0;i < a.length;i++){ 36 System.out.print(a[i]+" "); 37 } 38 } 39 40 public static void main(String[] args) { 41 int[] a=new int[]{2, 1, 5, 4, 9, 8, 6, 7, 10, 3}; 42 sort(a); 43 printArray(a); 44 45 } 46 47 }
浙公网安备 33010602011771号