//Sam Trivikraman CS1A Chapter 8, p. 488, #8
//
/*
******************************************************************************
Find Given Values
_______________________________________________________________________________
This program searches through a sorted array and finds the given value.
_______________________________________________________________________________
INPUT
the user's desired number : The number that the program searches for (user input)
OUTPUT
count : The number of times the linear/binary search iterates
_______________________________________________________________________________
*******************************************************************************
*/
//
#include <iostream>
using namespace std;
//implement a linear search to find the given value
int linSearch(int arr[], int num, int SIZE) {
int count; //OUTPUT keeps track of the number of times the linear search iterates through the array
count = 0;
//search for the value in the array
for(int i = 0; i < SIZE; i++)
{
if(num != arr[i])
{
count++;
}
else
{
return count;
}
}
//Output the number of times the search iterated through the array
return count;
}
//implement a binary search to find the given value
int binSearch(int arr[], int num, int SIZE) {
int firstPos = 0; //The position of the first value in the array
int lastPos = SIZE - 1; //The position of the last value in the array
int middlePos; //The position of the middle value in the array
int position = -1; //The position of the wanted value in the array
bool found = false; //a boolean flag
int count; //OUTPUT keeps track of the number of times the binary search iterates through the array
//search for the value in the array
while (!found && firstPos <= lastPos)
{
middlePos = (firstPos + lastPos) / 2;
if(arr[middlePos] == num)
{
found = true;
position = middlePos;
count = 1;
}
else if(arr[middlePos] > num)
{
lastPos = middlePos - 1;
count++;
}
else
{
firstPos = middlePos + 1;
count++;
}
//Output the number of times the search iterated through the array
return count;
}
return 0;
}
int main() {
//Data Dictionary
int SIZE = 20; //CONSTANT the size of the array
//INPUT the given array
int array[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int num; //the user inputted value that should be searched for
//Get the user inputted value
cout << "Please write a number." << endl;
cin >> num;
//Search for the value using a linear search
cout << linSearch(array, num, SIZE) << endl;
//Search for the value using a linear search
cout <<binSearch(array, num, SIZE) << endl;
return 0;
}