Find Equal (or Middle) Point in a sorted array with duplicates in C++

C++Server Side ProgrammingProgramming

Suppose we have one sorted array with n elements. The array is sorted. We have to find whether an element exists in an array from where the number of smaller element is same as the number of larger elements. If the equal point appears multiple times in the array, return the index of first occurrence. If no such point is present, then return -1. Suppose the elements are like A = [1, 1, 2, 3, 3, 3, 3, 3], then the equal point is at index 2, the element is A[2] = 2. As it has only one smaller element that is 1, and only one larger element, that is 3.

We will create one auxiliary array to store all distinct elements in it. If the count of distinct elements is even, then we cannot find any equal point, otherwise the middle element will be the mid-point.

Example

 Live Demo

#include<iostream>
using namespace std;
int searchEqualPoint(int arr[], int n) {
   int aux_arr[n];
   int i = 0, aux_index = 0;
   while (i < n) {
      aux_arr[aux_index++] = i++;
      while (i<n && arr[i] == arr[i-1])
         i++;
   }
   return (aux_index & 1)? aux_arr[aux_index>>1] : -1;
}
int main() {
   int arr[] = {1, 1, 2, 3, 3, 3, 3, 3};
   int n = sizeof(arr)/sizeof(arr[0]);
   int index = searchEqualPoint(arr, n);
   if (index != -1)
      cout << "Equal Point is: " << arr[index];
   else
      cout << "No Equal Point exists";
}

Output

Equal Point is: 2
raja
Published on 18-Dec-2019 09:13:50
Advertisements