Array binary search
In this chapter you will learn:
- Use the BinarySearch() method to search int Array for the number 5
- BinarySearch() returns a negative value in case of not found
- Binary search array element
- Use the BinarySearch() method to search charArray for 'o'
Do the binary search
using System;/*j a v a2s. co m*/
class MainClass
{
public static void Main()
{
int[] intArray = {5, 2, 3, 1, 6, 9, 7, 14, 25};
Array.Sort(intArray);
int index = Array.BinarySearch(intArray, 5);
Console.WriteLine("Array.BinarySearch(intArray, 5) = " + index);
}
}
The code above generates the following result.
Not found index
In case of a not found element the BinarySearch() returns a negative value and absolute value of the negative value is the value we should use to insert and still keep the array sorted.
using System;//from ja va 2 s . c om
class MainClass
{
public static void Main()
{
int[] intArray = {5, 2, 3, 1, 6, 9, 7, 14, 25};
Array.Sort(intArray);
int index = Array.BinarySearch(intArray, 4);
Console.WriteLine("Array.BinarySearch(intArray, 4) = " + index);
}
}
The code above generates the following result.
Binary search array element
using System;/* j a va2 s . co m*/
class MainClass
{
public static void Main()
{
string[] stringArray = {"t", "i", "a", "test", "abc123", "abc345"};
Array.Sort(stringArray);
int index = Array.BinarySearch(stringArray, "abc345");
Console.WriteLine("Array.BinarySearch(stringArray, \"abc345\") = " + index);
}
}
The code above generates the following result.
Binary search char array
using System;/*from j a va2 s . c om*/
class MainClass
{
public static void Main()
{
char[] charArray = {'w', 'e', 'l', 'c', 'o', 'm', 'e'};
Array.Sort(charArray); // sort the elements
int index = Array.BinarySearch(charArray, 'o');
Console.WriteLine("Array.BinarySearch(charArray, 'o') = " + index);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to copy an array to another array
- How to copy elements to another array
- Copy into middle of target
Home » C# Tutorial » Array