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

We wish to determine if the number 61 is stored. In search terminology, 61 is called the search key

or, simply, the key. The search proceeds as follows:

• Compare 61 with the 1st number, num[0], which is 35; they do not match so

we move on to the next number.

• Compare 61 with the 2nd number, num[1], which is 17; they do not match so

we move on to the next number.

• Compare 61 with the 3rd number, num[2], which is 48; they do not match so

we move on to the next number.

• Compare 61 with the 4th number, num[3], which is 25; they do not match so

we move on to the next number.

• Compare 61 with the 5th number, num[4], which is 61; they match, so the

search stops and we conclude that the key is in position 4.

But what if we were looking for 32? In this case, we will compare 32 with all the numbers in the

array and none of them will match. We conclude that 32 is not in the array.

Assuming the array contains n numbers, we can express the above logic as follows:

for h = 0 to n - 1

if (key == num[h]) then key found, exit the loop

endfor

if h < n then key found in position h

else key not found

This is a situation where we may want to exit the loop before we have looked at all elements in the

array. On the other hand, we may have to look at all the elements before we can conclude that the

key is not there.

If we find the key, we exit the loop and h will be less than n. If we exit the loop because h

becomes n, then the key is not in the array.

Let us express this technique in a function search that, given an int array num, an integer key, and

two integers lo and hi, searches for key from num[lo] to num[hi]. If found, the function returns

the position in the array. If not found, it returns -1. For example, consider the statement:

n = search(num, 61, 0, 6);

This will search num[0] to num[6] for 61. It will find it in position 4 and return 4, which is then

stored in n. The call

search(num, 32, 0, 6)

244

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!