0

My teacher wants me to search a typedef struct DATE d, in a dynamic array using binary search, I have no idea how to do that and I thought the purpose of binary search was to make things simpler and faster, I don't see the point of doing it here ...

Here the typedef struct date:

typedef struct date { /////////////////////////////////DATE
  int year;
  int month;
  int day;
} DATE;

And the function that I am currently using:

CALENDER_DAY *find_date(int i,ESTUDIO *est,DATE di){// suppose to be with binary search
  CALENDER_DAY *pcurrent=est->agenda[i].d; //it finds the calendar where I want to start looking 
  int size=est->agenda[i].sized;           //currently the size is 365 because I started with a year
  for (int k =0; k<size ; k++) {
    if(pcurrent->d.day==di.day && pcurrent->d.month==di.month && pcurrent->d.year==di.year){
      return pcurrent;
    }
  pcurrent++;
  }

  //realoc_memory(est,di.year,i);
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

1 Answers1

0

If dates are already sorted in d[] ...

To perform a binary search, some pseudo code to get OP started.

int lo = 0;
int hi = size - 1;
while (lo < hi) {
  int mid = lo + (hi-lo)/2;  // Get mid-pint without overflow
   
  // Compare mid with reference, return 0 on match, 1 when first > second, else -1
  int cmp = tbd_compare_fuction(&d[mid], di);
  if (cmp == 0) return &d[mid];  // found !
  if (cmp > 0) hi = mid - 1;
  else lo = mid + 1;
}
// Not found
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256