15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

416<br />

Using Indexes<br />

4. If the value at this pth location is less than the data you’re searching<br />

<strong>for</strong>, search the list to the right of the pth location. If the value at this<br />

pth location is greater than the data you’re searching <strong>for</strong>, search the<br />

list to the left of the pth location.<br />

5. Repeat Steps 1–4.<br />

Using Indexes<br />

Imagine yourself trying to find a certain store in a large shopping mall. You<br />

could wander up and down the corridors and examine each store, one by one,<br />

which is like a sequential search. Even if you use the various sequential search<br />

tactics, like block searching, sequential searching can still take a long time.<br />

Instead of searching each store sequentially, here’s a faster way: Look at the<br />

mall directory, find the store you want, and then walk straight to that store.<br />

That’s the difference between sequential searching and indexes. An index<br />

points you directly toward the item you want to find no matter how many<br />

items there may be. Indexes basically act like a shortcut to searching.<br />

Creating an index<br />

Indexes are similar to hash tables (see Book III, Chapter 3). The main difference<br />

is that a hash table calculates a unique value based on the total data<br />

stored whereas an index typically stores part of the data in a separate table<br />

that points to the rest of the data, as shown in Figure 2-7.<br />

Indexes are most often used in databases. If you organize a list of data in<br />

rows and columns with each column representing a field (such as Name or<br />

Phone Number) and each row representing a record (that contains one<br />

person’s name and phone number), an index can be as simple as a single<br />

column that consists of the data you’re most likely to use <strong>for</strong> searching.<br />

For example, if you have a database of names, addresses, and phone numbers,<br />

you probably spend more time looking up someone’s phone number by<br />

looking up his last name. So you could use the last name field as an index. At<br />

the simplest level, an index is nothing more than an organized list of existing<br />

data, such as a list of last names organized alphabetically (see Figure 2-7).<br />

If you create an index based on last names and you need to search by last<br />

name, an index can find your data faster. However, what if you want to<br />

search by phone number or city, but your index consists only of last names?<br />

In that case, you can create multiple indexes, one <strong>for</strong> each type of data.

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

Saved successfully!

Ooh no, something went wrong!