Given an array containing 1500 integers, write a C++ program that searches through the array for a user given value. (Hint: Use Sequential and Binary Search algorithms).
Below is the complete C++ code. If you face any difficulty while understanding the code, Please let me know in the comments.
Code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Function for sequential/linear search
void sequentialSearch(int arr[], int n, int target) {
for (int i=0;i<n;i++)
if(arr[i] == target) {
std::cout << "Sequential Search: Value found!" <<
std::endl;
return;
}
// Print message if target value not found in the array
std::cout << "Sequential Search: Value not found!" <<
std::endl;
}
// Function to perform binary Search
void binarySearch (int arr[], int n, int target) {
// Store the left and right indices
int left = 0, right = n - 1;
// Loop until left <= right
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is present at mid
if (arr[mid] == target) {
std::cout << "Binary Search: Value found!" <<
std::endl;
return;
}
// If target greater, ignore left half
if (arr[mid] < target)
left = mid + 1;
// If target is smaller, ignore right half
else
right = mid - 1;
}
std::cout << "Binary Search: Value not found!" <<
std::endl;
}
int main() {
// TODO: Add all your 1500 numbers into array
int arr[] = {2,3,14,5,6};
int n = sizeof(arr)/sizeof(arr[0]);
int target = 5;
// Call sequentialSearch function
sequentialSearch(arr, n, target);
// Sort the array
sort(arr, arr+n);
// Call binarySearch function
binarySearch(arr, n, target);
return 0;
}
Screenshots:
Output:
Get Answers For Free
Most questions answered within 1 hours.