Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The sequential search algorithm searches a list for a given item, starting with

ID: 3706282 • Letter: T

Question

The sequential search algorithm searches a list for a given item, starting with the first element in the list. It continues to compare the search item with the other elements in the list until either the item is found or the list has no more elements left to be compared with the search item. Implement a program that search for a value that is entered by the user in an array. The program should print a success message and tell the user the location of the value in the array in case it finds that value. Otherwise, should state that the value does not exist in the array. Then, extend the problem so that it searches for a value in a file.

Explanation / Answer

#include <iostream>
using namespace std;
int search(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;

if (arr[mid] == x)
return mid;

if (arr[mid] > x)
return search(arr, l, mid-1, x);

return search(arr, mid+1, r, x);
}

return -1;
}

int main()
{
int n;
cout<<" Size of array: ";
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}

int x;
cout<<" Number to search: ";
cin>>x;

int result = search(arr, 0, n-1, x);
(result == -1)? cout<<" Element is not present in array"
: cout<<" Element is present at index: "<<result;
return 0;
}?

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote