Finding the Last Occurrence of the element
Finding the Last Occurrence of the element in an given array using C++
two solutions can be possible as following bellow
//----RECURSIVE SOLUTION-----
#include <iostream>
int lastOcc(int arr[], int low, int high, int x, int n)
{
if (low > high)
return -1;
int mid = (low + high) / 2;
if (x > arr[mid])
return lastOcc(arr, mid + 1, high, x, n);
else if (x < arr[mid])
return lastOcc(arr, low, mid - 1, x, n);
else
{
if (mid == n - 1 || arr[mid + 1] != arr[mid])
return mid;
else
return lastOcc(arr, mid + 1, high, x, n);
}
}
int main()
{
int arr[] = {5, 10, 10, 10, 10, 20, 20};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "The size of the arr = " << n << std::endl;
int x = 10;
std::cout << "The index of the Last occurrence of the element is " << lastOcc(arr, 0, n - 1, x, n);
return 0;
}
/**/
0 Comments