160 likes | 577 Views
Binary Search. Determine where x is in the array a: private int[] a= {1,3,5,6,7,8,9,10,12,23,34,45,55,55,66,99};. public int binarySearch ( int a[], int x) { // Searches the array items a[0] through // a[a.length-1] for x by using a binary search. // mid is the return value
E N D
Binary Search Determine where x is in the array a: private int[] a= {1,3,5,6,7,8,9,10,12,23,34,45,55,55,66,99}; • public intbinarySearch(int a[], int x) • { • // Searches the array items a[0] through • // a[a.length-1] for x by using a binary search. • // mid is the return value • // Pre: a[0] <= a[1] <= ... <= a[a.length-1] • // && x is in a[0..a.length-1] • // Post: (x == a[mid]) && (0<= mid <= a.length-1) • // -- rewriting the first term of the postcondition: • // -- (a[mid] <= x < a[mid+1]) && (0 <= mid <= a.length-1)}
public intbinarySearch(int a[], int x) • { // Pre: a[0] <= a[1] <= ... <= a[a.length-1] • // && x is in a[0..a.length-1] • // Post: (a[mid] <= x < a[mid+1]) && (0 <= mid <= a.length-1)} Postcondition (mid is the working variable): x is in a[mid..mid+1) 0 mid mid+1 length-1 a: x //establish the invariant: int first= 0; int last= a.length-1; int mid= (first + last) / 2; while (!(a[mid] <= x && x < a[mid+1])) {//INV: a[first] <= x < a[last+1] && // 0<=first<=mid<=last<=a.length-1 //steps towards termination: //bring first and last closer //conserving the invariant: //making sure that x is still //between first and last } // end while Invariant (replace constants with var.) a[first] <= x < a[last+1] && 0<=first<=mid<=last<=a.length-1 0 first last length-1 a: ... ... ... Guard (the negation of what is missing to make the invariant equivalent to the postcondition – mid==first==last): !(a[mid] <= x && x < a[mid+1])
public int binarySearch(int a[], int x) { // Pre: a[0] <= a[1] <= ... <= a[a.length-1] // && x is in a[0..a.length-1] // Post: (x == a[mid]) && (0<= mid <= a.length-1) // -- (a[mid] <= x < a[mid+1]) && (0 <= mid <= a.length-1) int first= 0; int last= a.length-1; int mid= (first + last) / 2; while (!(a[mid] <= x && x < a[mid+1])) {//INV: a[first] <= x < a[last+1] // && 0<=first<=mid<=last<=a.length-1 if ( a[mid]<x )first = mid+1; else last= mid-1; mid = (first + last) / 2; } // end while return mid; } 0 first last length-1 a: ... ... ... mid