Array binary search

In this chapter you will learn:

  1. Use the BinarySearch() method to search int Array for the number 5
  2. BinarySearch() returns a negative value in case of not found
  3. Binary search array element
  4. Use the BinarySearch() method to search charArray for 'o'
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:

  1. How to copy an array to another array
  2. How to copy elements to another array
  3. Copy into middle of target
Home » C# Tutorial » Array
Array
Array loop
Array dimension
Jagged Array
Array length
Array Index
Array rank
Array foreach loop
Array ForEach Action
Array lowerbound and upperbound
Array Sort
Array search with IndexOf methods
Array binary search
Array copy
Array clone
Array reverse
Array ConvertAll action
Array Find
Array SequenceEqual