-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_and_last_occurrence_of_an_element.c++
94 lines (82 loc) · 2.25 KB
/
first_and_last_occurrence_of_an_element.c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*FIND FIRST AND LAST POSITIONS OF AN ELEMENT IN A SORTED ARRAY:
Given a sorted array with possibly duplicate elements, the task is to find indexes of first and last occurrences of an element x in the given array.
Example:
Input : arr[] = {1, 3, 5, 5, 5, 5 ,67, 123, 125}
x = 5
Output : First Occurrence = 2
Last Occurrence = 5*/
#include <bits/stdc++.h>
using namespace std;
int binarySearchForFirstOccurrence(int arr[], int n, int element)
{
int start = 0;
int end = n - 1;
int result = -1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (arr[mid] == element)
{
result = mid;
end = mid - 1;
}
else if (arr[mid] > element)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return result;
}
int binarySearchForLastOccurrence(int arr[], int n, int element)
{
int start = 0;
int end = n - 1;
int result = -1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (arr[mid] == element)
{
result = mid;
start = mid + 1;
}
else if (arr[mid] > element)
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return result;
}
int main()
{
int arr[] = {2, 4, 10, 10, 10, 10, 18, 20};
int n = sizeof(arr) / sizeof(arr[0]);
int element = 10;
int firstOccurrenecFoundAtIndex = binarySearchForFirstOccurrence(arr, n, element);
int lastOccurrenecFoundAtIndex = binarySearchForLastOccurrence(arr, n, element);
if (firstOccurrenecFoundAtIndex == -1)
{
cout << "The first occurrence of element " << element << " is not found in the array" << endl;
}
else
{
cout << "The first occurrence of element " << element << " is found at index: " << firstOccurrenecFoundAtIndex << endl;
}
if (lastOccurrenecFoundAtIndex == -1)
{
cout << "The last occurrence of element " << element << " is not found in the array" << endl;
}
else
{
cout << "The last occurrence of element " << element << " is found at index: " << lastOccurrenecFoundAtIndex << endl;
}
return 0;
}