0

Iam trying to code a single program of an array with 20 elements in it. It asks for a number from user and search is if this array has that number.

I am using Binary and selection search.

Its not giving me the required results. here is my code;

```
/* Linear and Binary search
*/
#include <iostream>
using namespace std;
// Function prototype
int searchList(int [], int , int );
int binarySearch(int [], int, int);
const int size = 20;
int main()
{
int tests[20]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int num1, num2;
int result1, result2;
//search the array for 19
result1 = searchList(tests, size ,19);
// if searchList returns -1 , then num1 is not found
cout << "Enter the number you wish to search for: ";
cin >> num1;
if (result1 == -1)
{
cout<<"There is no num1 "<<endl;
}
else
{
cout << "num1 is found"<<endl;
cout <<"and its position is =";
cout<< (result1+1)<<endl;
}
// calling Function for Binary search
result2 = binarySearch(tests , size, 19);
cout << "Enter the number you wish to search for: ";
cin >> num2;
if (result2 == -1)
cout << "That number does not exist in the array.\n";
else
{
cout << "That ID is found at element " << result2;
cout << " in the array.\n";
}
system("PAUSE");
return 0;
}
/*
**************************************
void displayList( int [], int)
{
}
/**********************************************************/
/*SearchList Function performs a linear search. Array name is list
and it has a max numElem elements .
if the number is found
If the number is found, its array
subscript is returned. Otherwise, -1 is returned. *
****************************************************************
*/
int searchList(int list [], int numElem, int value)
{
int index =0 ;
int position = -1;
bool found = false;
while (index < numElem && !found)
{
if (list [index]== value )
{
found = true ;
position= index;
}
index++;
}
return position;
}
//********************************************************************
/* The function should keep a count of the
number of comparisons it makes until it finds the value.
//***********************************************************************
/* Function for Binary search*/
int binarySearch(int array[], int numElems, int value)
{
int first = 0, // First array element
last = numElems - 1, // Last array element
middle, // Midpoint of search
position = -1; // Position of search value
bool found = false; // Flag
while (!found && first <= last)
{
middle = (first + last) / 2; // Calculate midpoint
}
if (array[middle] == value) // If value is found at midpoint
{
found = true;
position = middle;
}
else if (array[middle] > value) // If value is in lower half
{
last = middle - 1;
}
else
{
first = middle + 1; // If value is in upper half
}
return position;
}
```

*Edited 7 Years Ago by Nick Evan*: Snippet --> thread