
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary Search for Rational Numbers Without Floating Point Arithmetic in C
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
Advertisements