In: Computer Science
Write a C++ function which will search for TWO elements. The two elements must be right next to each other, contiguously. The prototype of the function should be: bool search_adjacent_elements(int const *x, size_t n, int target1, target2); It will return true if target1 and target2 exist in the array x somewhere, with target1 immediately to the left of target2. For example: int x[] = { 3, 5, 10, 14, 19, 25, 45, 60 }; cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 10, 14) << endl; // true!! cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 25. 19) << endl; // false (wrong order) cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 25, 60) << endl; // false (not right next to one another) You may assume the array is ordered. Your function must only search through your array once. If you search through your array multiple times (e.g., search once for target1, then search again for target2), you will receive a 2 mark deduction. You may use any code we have used in class as a reference. If referencing code from online, you must include a comment with a link to where you got it from. For a maximum 3/4 marks, do a linear search. For a maximum 4/4 marks, do a binary search.
CODE -
#include<iostream>
using namespace std;
// Function declaration
bool search_adjacent_elements(int const *x, size_t n, int target1, int target2);
// Main function
int main()
{
int x[] = { 3, 5, 10, 14, 19, 25, 45, 60 };
// This is required to print bool values as true/false because by default C++ prints 1 for true and 0 for false
cout << boolalpha;
cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 10, 14) << endl;
cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 25, 19) << endl;
cout << search_adjacent_elements(x, sizeof x / sizeof x[0], 25, 60) << endl;
return 0;
}
// Function definition
bool search_adjacent_elements(int const *x, size_t n, int target1, int target2)
{
// Variable declaration
int l = 0;
int r = n - 1;
int m;
// Loop to implement binary search
while(l <= r)
{
m = l + (r - l)/2;
// Search for target1 and check if next element is equal to target2 or not
// Check if target is present at the mid
if(x[m] == target1)
{
if (x[m+1] == target2)
return true;
else
return false;
}
// If target1 is greater than mid, search only in right half
else if (x[m] < target1)
l = m + 1;
// If target1 is smaller than mid, search only in left half
else
r = m - 1;
}
// Return false if both elements were not found adjacent to each other
return false;
}
SCREENSHOTS -
CODE -
OUTPUT -
If you have any doubt regarding the solution, then do
comment.
Do upvote.