Binary Search for Rational Numbers without using floating point arithmetic in C program

CServer Side ProgrammingProgramming

In this problem, we are given a sorted array of rational numbers. and we have to search the given element using binary search algorithm for this rational number array without using floating point arithmetic.

A Rational number is number represented in the form p/q where both p and q are integers. For example, ⅔, ⅕.

Binary search is searching technique that works by finding the middle of the array for finding the element.

for finding the element using binary search from a sorted array of rational numbers, where floating point arithmetic are not allowed. We will compare the numerators and denominators to find which element is Greater or which one is element that is to be found.

Example

Let's create a program for this,

#include <stdio.h>
struct Rational {
   int p;
   int q;
};
int compare(struct Rational a, struct Rational b) {
   if (a.p * b.q == a.q * b.p)
      return 0;
   if (a.p * b.q > a.q * b.p)
      return 1;
   return -1;
}
int binarySearch(struct Rational arr[], int l, int r, struct Rational x) {
   if (r >= l) {
      int mid = l + (r - l)/2;
   if (compare(arr[mid], x) == 0) return mid;
   if (compare(arr[mid], x) > 0)
      return binarySearch(arr, l, mid-1, x);
   return binarySearch(arr, mid+1, r, x);
   }
   return -1;
}
int main() {
   struct Rational arr[] = {{1, 4}, {2, 3}, {3, 2}, {7, 2}};
   struct Rational x = {3, 2};
   int n = sizeof(arr)/sizeof(arr[0]);
   printf("Element found at index %d", binarySearch(arr, 0, n-1, x));
}

Output

Element found at index 2
raja
Published on 22-Nov-2019 13:44:53
Advertisements