260 Arrays Chapter 7 7.8 Searching (Web design tools) Arrays: Linear

260 Arrays Chapter 7 7.8 Searching Arrays: Linear Search and Binary Search Often, programmers work with large amounts of data stored in arrays. It might be necessary in this case to determine whether an array contains a value that matches a certain key value. The process of locating a particular element value in an array is called searching. In this section, we discuss two searching techniques the simple linear search technique and the more efficient binary search technique. Exercises 7.8 and 7.9 at the end of this chapter ask you to implement recursive versions of the linear and binary search. 7.8.1 Searching an Array with Linear Search In the program in Fig. 7.11, method LinearSearch (defined on lines 44 54) uses a for structure containing an ifstructure to compare each element of an array with a search key (line 44). If the search key is found, the method returns the subscript value for the element to indicate the exact position of the search key in the array. If the search key is not found, the method returns 1. (The value 1 is a good choice because it is not a valid subscript number.) If the elements of the array being searched are not in any particular order, it is just as likely that the value will be found in the first element as in the last. On average, the program will have to compare the search key with half the elements of the array. The program contains a 100-element array filled with the even integers from 0 198. The user types the search key in a TextBox (called inputTextBox) and clicks the findButton to start the search. [Note: The array is passed to LinearSearch even though the array is an instance variable of the class. This is done because an array normally is passed to a method of another class for searching.] 1 // Fig. 7.11: LinearSearcher.cs 2 // Demonstrating linear searching of an array. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class LinearSearcher : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button searchButton; 13 private System.Windows.Forms.TextBox inputTextBox; 14 private System.Windows.Forms.Label outputLabel; 15 16 int[] a = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 17 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 }; 18 19 // Visual Studio .NET generated code 20 21 [STAThread] 22 static void Main() 23 { Fig. 7.11 Linear search of an array. (Part 1 of 2.)
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

Leave a Reply