15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2: Searching Algorithms<br />

In This Chapter<br />

Conducting sequential and binary tree searches<br />

Using an index<br />

Comparing search algorithms<br />

One of the most common functions of a computer program is searching.<br />

A database needs to search through names and addresses, a word<br />

processor needs to search through text, and even a computer chess game<br />

needs to search through a library of moves to find the best one.<br />

Because searching is such an important part of computer <strong>programming</strong>,<br />

computer scientists have developed a variety of algorithms to search <strong>for</strong><br />

data. When searching <strong>for</strong> data, the main limitation is time. Given enough<br />

time, any search algorithm can find what you want, but there’s a big difference<br />

between finding data in five seconds or five hours.<br />

The time a search algorithm takes is always related to the amount of data to<br />

search, which is the search space. The larger the search space, the slower<br />

the search algorithm. If you only need to search a small search space, even a<br />

simple and slow search algorithm is fast enough.<br />

The two main categories of search algorithms are<br />

✦ Unin<strong>for</strong>med (or brute-<strong>for</strong>ce)<br />

✦ In<strong>for</strong>med (or heuristic)<br />

Unin<strong>for</strong>med, or brute-<strong>for</strong>ce, search algorithms work by simply examining the<br />

entire search space, which is like losing your car keys in your apartment and<br />

searching every apartment in the entire building. Eventually, you find your<br />

keys, but it may take a long time to do it.<br />

In<strong>for</strong>med, or heuristic, search algorithms work by selectively examining the<br />

most likely parts of the search space. This is like losing your car keys in your<br />

apartment but only examining the bedroom where you last saw your car keys.<br />

By using knowledge of the search space, in<strong>for</strong>med search algorithms can speed<br />

up a search algorithm by eliminating obvious parts of the search space that<br />

don’t contain the data you want to find.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!