19.12.2012 Views

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

Computer Programming Concepts and Visual Basic David I. Schneider

SHOW MORE
SHOW LESS

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

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

172 <strong>Computer</strong> <strong>Programming</strong> <strong>Concepts</strong> <strong>and</strong> <strong>Visual</strong> <strong>Basic</strong><br />

Ordered arrays can be searched more efficiently than unordered arrays. In this section<br />

we use their order to shorten the search. The technique used here is applied to searching<br />

sequential files in Section 7.<br />

EXAMPLE 1<br />

The following program places an ordered list of names into an array, requests a name as input, <strong>and</strong><br />

informs the user if the name is in the list. Because the list is ordered, the search of the array ends when<br />

an element is reached whose value is greater than or equal to the input name. On average, only half the<br />

ordered array will be searched. Figure 6-5 shows the flowchart for this search.<br />

‘Create array to hold 10 strings<br />

Dim nom(1 To 10) As String<br />

Private Sub cmdSearch_Click()<br />

Dim n As Integer, name2Find As String<br />

‘Search for a name in an ordered list<br />

name2Find = UCase(Trim(txtName.Text))<br />

n = 0 ‘n is the subscript of the array<br />

Do<br />

n = n + 1<br />

Loop Until (nom(n) >= name2Find) Or (n = 10)<br />

‘Interpret result of search<br />

picResult.Cls<br />

If nom(n) = name2Find Then<br />

picResult.Print “Found.”<br />

Else<br />

picResult.Print “Not found.”<br />

End If<br />

End Sub<br />

Private Sub Form_Load()<br />

‘Place the names into the array<br />

‘All names must be in uppercase<br />

nom(1) = “AL”<br />

nom(2) = “BOB”<br />

nom(3) = “CARL”<br />

nom(4) = “DON”<br />

nom(5) = “ERIC”<br />

nom(6) = “FRED”<br />

nom(7) = “GREG”<br />

nom(8) = “HERB”<br />

nom(9) = “IRA”<br />

nom(10) = “JUDY”<br />

End Sub<br />

[Run, type Don into the text box, <strong>and</strong> click the comm<strong>and</strong> button.]

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

Saved successfully!

Ooh no, something went wrong!