C++/hi

Advertisement


Question
can you tell me what a difference between binary and linear search?using examples?

Answer
Hello raymond, thank you for the question.

A binary search usually starts from the middle of a collection and continues subdividing the collection based on whether the number it is searching for is greater than, or less than the current number. If the middle is the number being searched, the search ends. If it's less than the middle, then it splits the "left" segment of the collection and performs the same search again. Think of searching a tree structure starting at the root node. If it's less than the root, it searches the left children, if it's greater, it searches the right children, simply repeating itself.

         o
         0   0
         0  0 0 0
A linear search is like searching each value in an array.

int toSearch = 3;
int array[3] = {1, 2, 3};

for(int i = 0; i < 3; i++)
{
if(array[i] == toSearch)
{
// found it.
}
}

It goes through each value sequentially (or you could think of it like searching each element in line) until it finds the value or hits the end of the collection.

Detailed examples can be found on Wikipedia.

http://en.wikipedia.org/wiki/Binary_search
http://en.wikipedia.org/wiki/Linear_search

I hope this information was helpful.

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.