/***************************************************************
* Name: Prof. Orta
* Course: Computer Science & Programming
* Class: CS04103 Section: 1 & 2
* Assignment Date: 10/27/20
* File Name: LinearSearchcpp
*****************************************************************
* ID: 001
* Purpose: Explain Binary Search in C++
*****************************************************************/
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
int main()
{
// Declaring variables
int array[10];
int value = 0, counter = 0, temp = 0, medium = 0, left = 0, right = 8;
// Inserting random numbers to the array of 10 elements.
srand (time(0));
for (int x = 0 ; x < 9 ; x++)
{
array[x] = rand() % 9 + 1;
}
// Displaying the array unsorted
system("clear");
cout << "\n ------ Array to search unsorted ----" << endl;
cout << "\n -------------------------------------" << endl;
for (int x = 0 ; x < 9 ; x++)
{
cout << " | " << array[x];
}
cout << " |\n -------------------------------------" << endl;
// Sorting the array ascending using selection sort algorithm
for(int x=0; x < 9; x++)
{
for( int y = x+1; y < 9; y++)
{
if(array[x]>array[y])
{
temp =array[x];
array[x]=array[y];
array[y]=temp;
}
}
}
// Displaying the array sorted
cout << "\n ------ Array to search sorted ----" << endl;
cout << "\n -------------------------------------" << endl;
for (int x = 0 ; x < 9 ; x++)
{
cout << " | " << array[x];
}
cout << " |\n -------------------------------------" << endl;
// Asking for the number to search for
cout << "\nPlesse enter the number you want to search for: ";
cin >> value;
cout << endl;
// Searching for the value using binary search
while (left <= right)
{
int medium = left + (right - left) / 2;
counter++;
cout << "\nSearch #: " << counter << " the middle index of the array is: " << medium;
// Check if value is present at mid
if (array[medium] == value)
cout << "\n\nFound the value: " << value << " in the array index: " << medium;
// If x greater, ignore left half
if (array[medium] < value)
left = medium + 1;
// If x is smaller, ignore right half
else
right = medium - 1;
}
return 0;
}