[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Sort and search arrays in C#

[Sort and search arrays in C#]

The Array class provides several useful methods for working with arrays. Two of them let you sort and search arrays.

The following code shows how the program 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 in the array. 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 happens to find 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.

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.