Question

C++ C++ C++ Write a program that will provide evidence as to which algorithm will search...

C++ C++ C++ Write a program that will provide evidence as to which algorithm will search an array faster, Linear (sequential) search or Binary Search. Your program should test many different scenarios. Please help with right answer.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,

If the data is sorted then binary search algorithm is the best, else linear search is the best

let us assume our data is sorted then :

The worst-case and average-case time complexity for binary search is O(log n).

The worst-case and average-case time complexity is O(n).

As we know that  O(log n) is always lesser than O(n) [ O(log n) < O(n) ]
The following example shows the binary search is better than linear search

/* C++ Program - Binary Search */
        
#include<iostream.h>
#include<conio.h>
void main()
{
        clrscr();
        int n, i, arr[50], search, first, last, middle;
        cout<<"Enter total number of elements :";
        cin>>n;
        cout<<"Enter "<<n<<" number :";
        for (i=0; i<n; i++)
        {
                cin>>arr[i];
        }
        cout<<"Enter a number to find :";
        cin>>search;
        first = 0;
        last = n-1;
        middle = (first+last)/2;
        while (first <= last)
        {
                if(arr[middle] < search)
                {
                        first = middle + 1;

                }
                else if(arr[middle] == search)
                {
                        cout<<search<<" found at location "<<middle+1<<"\n";
                        break;
                }
                else
                {
                         last = middle - 1;
                }
                middle = (first + last)/2;
        }
        if(first > last)
        {
                cout<<"Not found! "<<search<<" is not present in the list.";
        }
        getch();
}
Add a comment
Know the answer?
Add Answer to:
C++ C++ C++ Write a program that will provide evidence as to which algorithm will search...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT