Iterative binary search int bsearch(int* al int size, int x) int low=0, high=size-1 while (low<=higt int mid=(low+high)/2 f(a[mid<x low-mid+1 else if (x<a[mid]) high=mid-1 else return mid; return -1
11 int bsearch(int* a[],int size,int x) { int low=0, high=size-1; while (low<=higt) { int mid=(low+high)/2; if (a[mid]<x) low=mid+1; else if (x<a[mid]) high=mid-1; else return mid; } return -1 } Iterative binary search:
Iterative binary search int bsearch(int* al int size, int x) int low=0, high=size-1 while (low<=higt int mid=(low+high)/2 f(a[mid<x low-mid+1 else if (x<a[mid]) high=mid-1 else return mid; return -1 ni+1<=ni/2 ie.ni<=(N1)2i-1} N stops at 1 or below there are at most 1+k iterations where k is the smallest such that(N1)/2Kk-1}<=1 so k is at most 2+log(N-1) O(log N)
12 int bsearch(int* a[],int size,int x) { int low=0, high=size-1; while (low<=higt) { int mid=(low+high)/2; if (a[mid]<x) low=mid+1; else if (x<a[mid]) high=mid-1; else return mid; } return -1 } Iterative binary search: n=high-low n_i+1 <= n_i / 2 i.e. n_i <= (N-1)/2^{i-1} N stops at 1 or below there are at most 1+k iterations, where k is the smallest such that (N-1)/2^{k-1} <= 1 so k is at most 2+log(N-1) O(log N)
13 Recursive binary search int bsearch(int* al, int low, int high, int x) f (low>high) return -l; 0(1) e⊥se int mid=(lowthigh)/2 f (x=a [mid] return mid; 0(1) else if(a [mid]<x bsearch(a, mid+l high, x)i T(N/2) lse bsearch(a low, mid-1)i 7(N)=7(~)+
13 O(1) T(N/2) int bsearch(int* a[],int low, int high, int x) { if (low>high) return -1; else int mid=(low+high)/2; if (x=a[mid]) return mid; else if(a[mid]<x) bsearch(a,mid+1,high,x); else bsearch(a,low,mid-1); } O(1) Recursive binary search: ) 1 2 ( ) ( (1) 1 = + = N T N T T
Solving the recurrence 7(N)=T() T()+3 7(一)+k With 2K=N(or asymptotically), k=log N, we have g Thus, the running time is O(log N
14 With 2k = N (or asymptotically), k=log N, we have Thus, the running time is O(log N) T(N) = k = log N k N T N T N T N T N T k = + = = + = + = + ) 2 ( ) 3 8 ( ) 2 4 ( ) 1 2 ( ) ( Solving the recurrence:
Advantages and disadvantages of different implementations of a list Static Dynamic Lin ked array array list Insertion Deletion Search
15 Advantages and disadvantages of different implementations of a list Static array Dynamic array Linked list Insertion Deletion Search