VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-search-for-rational-numbers-without-using-floating-point-arithmetic/

⇱ Search in an Array of Rational Numbers without floating point arithmetic - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Search in an Array of Rational Numbers without floating point arithmetic

Last Updated : 12 Mar, 2025

Given a sorted array of rational numbers, where each rational number is represented in the form p/q (where p is the numerator and q is the denominator), the task is to find the index of a given rational number x in the array. If the number does not exist in the array, return -1.

Examples:  

Input: arr[] = [1/5, 2/3, 3/2, 13/2], x = 3/2
Output: 2
Explanation: The given rational element is present at index 2.

Input: arr[] = [1/5, 2/3, 3/2, 13/2], x = 5/1
Output: -1
Explanation: The given rational number 5/1 does not exist in the array.

Input: arr[] = [1/2, 2/3, 3/4, 4/5], x = 1/2
Output: 0
Explanation: The given rational number 1/2 is present at index 0 in the array.

Approach:

The idea is to use binary search to efficiently find the index of the given rational number x in the sorted array of rational numbers. Since the array is sorted, we can compare rational numbers without using floating-point arithmetic by cross-multiplying the numerators and denominators, allowing us to determine whether to search in the left or right half of the array.

Step by step approach:

  1. Initialize two pointersleft and right, to represent the start and end of the search range in the array.
  2. Calculate the middle index of the current search range using mid = left + (right - left) / 2.
  3. Compare the middle element with x using cross-multiplication:
    • If arr[mid] == x, return mid (index found).
    • If arr[mid] > x, update right = mid - 1 to search in the left half.
    • If arr[mid] < x, update left = mid + 1 to search in the right half.
  4. Repeat steps 2-3 until left exceeds right.
  5. If the loop ends without finding x, return -1 (element not found).

Output
2

Time Complexity: O(log n)
Auxiliary Space: O(1),  since no extra space has been taken. 

Comment