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;
}
Ancient Dragon commented: This should not have been a code snippet. -5

Dani AI

Generated

Two issues were already spotted in the thread by (calling the search before reading input, and the misplaced brace that made the while loop empty). To answer ’s followup about “how many passes”: treat each element comparison as a pass and increment a counter inside the loop. The snippet below shows one safe way to do both searches and return the comparison count via a reference parameter.

#include <iostream>

int linear_search(const int a[], int n, int target, int &comps) {
    comps = 0;
    for (int i = 0; i < n; ++i) {
        ++comps;                  // one comparison per inspected element
        if (a[i] == target) return i;
    }
    return -1;
}

int binary_search(const int a[], int n, int target, int &comps) {
    comps = 0;
    int lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        ++comps;                  // compare a[mid] with target
        if (a[mid] == target) return mid;
        if (a[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1;
}

int main() { /* build sorted array, read input, call the two functions and print pos + comps */ }

Notes and quick rules:

  • Binary search requires a sorted array; otherwise results are meaningless.
  • Define exactly what you count. The code above counts “comparisons of an array element to the target.” For linear search worst-case = n (20 here); average ≈ n/2. For binary search worst-case = floor(log2(n)) + 1 comparisons (for n=20 that is 5).
  • Common pitfalls: misplaced braces (make sure the loop body actually contains the comparisons), calling functions before reading input, and off-by-one when printing a user-facing position (convert 0-based index to 1-based if you prefer).
  • To report counts back to the caller use a reference parameter (as above), a return struct/pair, or global (less recommended).

Recommended Answers

All 6 Replies

Look at the order you are using the search functions.
You call the function, looking for a fixed number.
You then ask the user to enter a search value.
You then test the result of your search, for that fixed number, which is not the user's input (most of the time, anyway.)

How about:
Ask user for number.
Call the function, using that input variable as the search key
Then evaluate the result from the function and display found/not found message.

I updated the codes but still it doesnt do binary search!!!! why?/ can any one find out what i am doing wrong here

/* 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




// if searchList  returns -1 , then num1 is not found
cout << "Enter the number you wish to search for: ";
cin >> num1;

result1 = searchList(tests, size ,num1);
   if (result1 == -1)
   {
       cout<<"There is no "<<num1<< "Enter again"<<endl;
       cin>>num1;
   }
   
   else 
   {
       cout << "your number is found"<<endl;
       cout <<"and its position is =";
       cout<< (result1+1)<<endl; 
       
   }
    // calling II Function for Binary search
    
result2 = binarySearch(tests , size, num2);
    
cout << "Enter the number you wish to search for: ";
cin >> num2;
result2 = binarySearch(tests , size, 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. The*/



//***********************************************************************
/* 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;
}

Proper indenting would help you find the error.

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
	}

Can you see it now?

Proper indenting would help you find the error.

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
	}

Can you see it now?

Ok i caught the error

Now How Can i find how many pass both searches are making.

Now How Can i find how many pass both searches are making.

Put a counter in the loop. Display the results before the function returns, or pass it back as reference parameter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.