Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Searching an array

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How would I write a function that searches an array to find an inputed number and returns a one if true and a 0 if false.
 
The simple way is to use the .BinarySearch method on the array.
Code:
int iFound;
String sLastName = "Jones";

iFound = Array.BinarySearch(MyArray, sLastName);
if (iFound < 0) then 
{
   // Not found
} 
else
{
   // iFound contains the index of the found element
}

The values in the array and the value must implement the IComparable interface. The String class does this for you, but if you have your own class stored in the array, it will have to implement the IComparable interface. This means that you should include a function in your class:
Code:
   int CompareTo(
      object obj
   );
that compares the object passed in to the current instance (the 'this' object). You should return one of three values:

-1 : 'this' is less than obj
0 : 'this' is equal to obj
1 : 'this' is greater than obj

This function gets called by the BinarySearch method, and you tell it if it's low or high.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top