Use the Array class's Sort and BinarySearch methods in C#

The Array class provides several useful methods for working with arrays. The following code uses the Array class's Sort method to sort an array of random data.

// The data values.
private const int NumValues = 100;
private int[] Values;

// Make some random values.
private void Form1_Load(object sender, EventArgs e)
{
// Generate random values.
Random rand = new Random();
Values = new int[NumValues];
for (int i = 0; i < NumValues; i++)
{
Values[i] = rand.Next(0, 100);
}

// Sort the values.
Array.Sort(Values);

// Display the values.
lstValues.DataSource = Values;
}

This code creates a Random object and the Values array. It then loops through the array assigning random values to each entry.

Next the code calls the Array class's Sort method to sort the values. It finishes by displaying the values in a ListBox.

The following code shows how the program uses the Array class's BinarySearch method to find a value in the array.

// Find a value.
private void btnSearch_Click(object sender, EventArgs e)
{
// Get the target value.
int target = int.Parse(txtValue.Text);

// Try to find it.
int index = Array.BinarySearch(Values, target);

// Select the value.
if (index >= 0)
{
// We found the target. Select it.
lstValues.SelectedIndex = index;
}
else
{
// We didn't find the target. Select a nearby value.
index = -index;
if (index >= NumValues) index = NumValues - 1;
lstValues.SelectedIndex = index;
}
}

The code parses the text you entered and calls the Array class's BinarySearch method to find the value. If BinarySearch finds the value, it returns the value's index in the array. If the value appears more than once in the array, BinarySearch returns the index of an arbitrary item with the target value. (It just returns whichever value it finds first during its search.)

If the value is not in the array, BinarySearch returns the negative of the last index it examined while searching. If the negative of the returned value is not outside of the array's bounds, then it gives the index of a value that's sort of near where the target value would be if it were present. The position may not be exactly where the target item would be but it should be fairly close.

(Note that BinarySearch only works if the array is sorted.)

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.