

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 using floating point arithmetic in C program
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
- Related Questions & Answers
- Decimal fixed point and floating point arithmetic in Python
- C Program to Multiply two Floating Point Numbers?
- Signed floating point numbers
- Program to find GCD of floating point numbers in C++
- Java program to multiply given floating point numbers
- Java Program to Multiply Two Floating-Point Numbers
- Is 'floating-point arithmetic' 100% accurate in JavaScript?
- C++ Floating Point Manipulation
- Floating point comparison in C++
- Binary Search using pthread in C Program?
- Equal Rational Numbers in C++
- 8085 program for Binary search
- Python Program for Binary Search
- C Program for Binary Search (Recursive and Iterative)?
- Python Program to Implement Binary Search without Recursion
Advertisements