Todo
This is completely in draft mode now and is at best in placeholder status. No revisions please.
In this section, we’ll take a look at how to search for a value in an array. Although a fairly straightforward topic, it is one that comes up repeatedly in programming.
These examples make use of arrays and loops, not to mention functions (for putting it all together). You’ll also begin to see greater use of the return statement and return values (the results of functions).
By far, one of the most common searches you will see in typical programs. It also happens to be one of the more misused searches, which is another reason we want you to know about it.
Here is the code to perform a linear search for an integer in an array:
1 2 3 4 5 6 7 | public static int IntArrayLinearSearch(int[] data, int item) {
int N=data.Length;
for (int i=0; i < N; i++)
if (data[i] == item)
return i;
return -1;
}
|
Here’s what it does:
1 2 3 4 5 6 7 8 9 | public static int IntArrayLinearSearch(int[] data, int item, int start) {
int N=data.Length;
if (start < 0)
return -1;
for (int i=start; i < N; i++)
if (data[i] == item)
return i;
return -1;
}
|
The following code shows how to use the linear search:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public static void Main (string[] args)
{
Console.WriteLine ("Please enter some integers, separated by spaces:");
string input = Console.ReadLine();
string[] integers = input.Split(' ');
for (int i=0; i < integers.Length; i++)
Console.WriteLine("i={0} integers[i]={1}", i, integers[i]);
int[] data = new int[integers.Length];
for (int i=0; i < data.Length; i++)
data[i] = int.Parse(integers[i]);
for (int i=0; i < data.Length; i++)
Console.WriteLine("i={0} data[i]={1}", i, data[i]);
while (true) {
Console.WriteLine("Please enter a number you want to find (blank line to end):");
input = Console.ReadLine();
if (input.Length == 0)
break;
int searchItem = int.Parse(input);
Console.WriteLine("Please enter a position to start searching from (0 for beginning): ");
input = Console.ReadLine();
int searchPos = int.Parse(input);
int foundPos = IntArrayLinearSearch(data, searchItem, searchPos);
if (foundPos < 0)
Console.WriteLine("Item {0} not found", searchItem);
else
Console.WriteLine("Item {0} found at position {1}", searchItem, foundPos);
}
}
}
}
|
In this example, we ask the user to enter an array of data by entering the values one at a time. As we’ve learned before, Console.ReadLine() gives us a string, which we can then split using the Split() method. (It is important that the items in this array are only separated by a single space character as Split() is not flexible to handle extra spaces.
Once we have gotten the input text split into an array of string (string[]), we set up a simple loop (on lines 7-8) to convert each item in the string array into an integer.
The rest is mostly self-explanatory.