int search(int A[], int n, int target) { int k = _keyIndex(A, n); // n==0 or n > 0 bool positive = (A[0] <= A[k]); int u = _binarySearch(A, 0, k, positive, target); if(-1 == u) u = _binarySearch(A, k + 1, n - 1, positive, target); return u; }
int _binarySearch(int *a, int start, int end, int x){ if(start > end) return -1; int mid = (start+end)/2; if(a[mid] == x){ int ind = _binarySearch(a, start, mid-1, x); if(ind == -1) return mid; } else if(a[mid] > x) return _binarySearch(a, start, mid-1, x); else return _binarySearch(a, mid+1, end, x); }
int containsDynArrOrd(DynArr *v, TYPE val, comparator compare){ int idx = _binarySearch(v, val, compare); // rem: if it's not in there, it'll return size. This could hold a previously added value...so must check the index! if (EQ(v->data[idx],val) && idx < v->size) return 1; else return 0; }
bool isMajority(int *a, int n, int x){ int ind = _binarySearch(a, 0, n-1, x); if(ind == -1) return false; if(a[ind+n/2] == x) return true; return false; }
void removeDynArrOrd(DynArr *v, TYPE val, comparator compare) { int idx = _binarySearch(v, val, compare); if(EQ(v->data[idx], val)) removeAtDynArr(v, idx); }
void addDynArrOrd(DynArr *v, TYPE val, comparator compare) { int idx = _binarySearch(v, val, compare); printf("Adding to index = %d\n", idx); addAtDynArr(v,idx,val); }