Find position of an element in a sorted array of infinite numbers in C++

C++Server Side ProgrammingProgramming

In this problem we are given an array consisting of infinite sorted numbers. Our task is to Find position of an element in a sorted array of infinite numbers.

Let’s take an example to understand the problem,

Input

arr[] = {2, 4, 6, 8, 9, 12, 14,17, ….}, ele = 9

Output

4

Explanation

Solution Approach

For searching elements from a sorted array efficiently, we will be using the binary searching method. Here, single the end point is not known, we will modify the algorithm a bit.

We will fix the start pointer to first position, then take the end pointer to second position. After this, we will check for the value at the end pointer and increment it by doubling it if the value is less than key and update the start pointer with the last position of the end pointer.

When the last position value is greater than the element to be found, we will search in this subarray using binary search.

Program to illustrate the working of our solution,

Example

 Live Demo

#include<iostream>
using namespace std;
int binarySearch(int arr[], int start, int end, int ele) {
   if (end >= start) {
      int mid = start + (end - start)/2;
      if (arr[mid] == ele)
         return mid;
      if (arr[mid] > ele)
         return binarySearch(arr, start, mid-1, ele);
      return binarySearch(arr, mid+1, end, ele);
   }
   return -1;
}
int findPos(int arr[], int value) {
   int start = 0, end = 1;
   while (arr[end] < value) {
      start = end;
      end = 2*end;
   }
   return binarySearch(arr, start, end, value);
}
int main(){
   int arr[] = {1, 2, 4, 6, 8, 9, 12, 14, 17, 21, 45};
   int index = findPos(arr, 9);
   if (index == -1)
      cout<<"Element not found!";
   else
      cout<<"Element found! index = "<<index;
   return 0;
}

Output

Element found! index = 5
raja
Published on 16-Mar-2021 05:09:45
Advertisements