08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

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

Chapter 9 ■ Searching, Sorting, and Merging

will return -1 since 32 is not stored in the array. Here is the function, search:

int search(int num[], int key, int lo, int hi) {

//search for key from num[lo] to num[hi]

for (int h = lo; h <= hi; h++)

if (key == num[h]) return h;

return -1;

} //end search

We first set h to lo to start the search from that position. The for loop ‘steps through’ the

elements of the array until it finds the key or h passes hi.

To give an example of how a search may be used, consider the voting problem of the last chapter.

After the votes have been tallied, our arrays name and vote look like this (remember we did not

use name[0] and vote[0]):

1 Victor Taylor 4

2 Denise Duncan 3

3 Kamal Ramdhan 6

4 Michael Ali 4

5 Anisa Sawh 6

6 Carol Khan 2

7 Gary Olliverie 3

Suppose we want to know how many votes Carol Khan received. We would have to search for her

name in the name array. When we find it (in position 6), we can retrieve her votes from vote[6]. In

general, if a name is in position n, the number of votes received will be vote[n].

We modify our search function to look for a name in the name array:

//search for key from name[lo] to name[hi]

int search(char name[][MaxNameLength+1], char key[], int lo, int hi) {

for (int h = lo; h <= hi; h++)

if (strcmp(key, name[h]) == 0) return h;

return -1;

}

Recall that we compare two strings using strcmp. And in order to use any predefined string

function, we must use the directive

#include <string.h>

at the head of our program.

245

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!