How to use Array.BinarySearch() method to search in Array of int objects in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Array intArray = Array.CreateInstance(typeof(Int32), 5);

            intArray.SetValue(12, 0);
            intArray.SetValue(11, 1);
            intArray.SetValue(27, 2);
            intArray.SetValue(73, 3);
            intArray.SetValue(32, 4);

            Array.Sort(intArray);

            PrintArray(intArray);

            object o = 27;
            FindObject(intArray, o);

            o = 114;
            FindObject(intArray, o);
        }
        public static void PrintArray(Array arr)
        {
            int cols = arr.GetLength(arr.Rank - 1);

            foreach (object o in arr)
                Console.Write("  {0}", o);

            Console.WriteLine();
        }
        public static void FindObject(Array arr, object o)
        {
            int index = Array.BinarySearch(arr, o);

            if (index < 0)
                Console.WriteLine("Object: {0} not found", o);
            else
                Console.WriteLine("Object found: {0} at index {1}", o, index);
        }
    }
}


/*
run:
 
  11  12  27  32  73
Object found: 27 at index 2
Object: 114 not found
 
*/

 



answered Apr 9, 2016 by avibootz

Related questions

2 answers 257 views
1 answer 180 views
1 answer 138 views
138 views asked Dec 3, 2020 by avibootz
1 answer 160 views
160 views asked Apr 29, 2020 by avibootz
...