Friday, 26 January 2018

Binary search to find specific element

In Binary search - The given array should be in sorted already.

Now, find specific element : 10


Exp:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinarySearchTest
{
    public static class BinarySearch
    {
        public static Dictionary<int, int> BinarySearchToFindElementWithIndex(int[] array, int findElement)
        {
            Dictionary<int, int> dictionary = new  Dictionary<int, int>(){ };
            int startIndex = 0; int midIndex = 0;
            int endIndex = array.Length - 1;

            while (startIndex <= endIndex)
            {
                midIndex = (startIndex + endIndex) / 2;

                if (array[midIndex] > findElement)
                {
                    endIndex = midIndex - 1;
                }
                else if (array[midIndex] < findElement)
                {
                    startIndex = midIndex + 1;
                }
                else if (array[midIndex] == findElement)
                {
                    dictionary.Add(midIndex, findElement);
                    break;
                }
            }
            return dictionary;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 4, 5, 6, 10, 12, 20 };
            Dictionary<int,int> findElement = BinarySearch.BinarySearchToFindElementWithIndex(array,10);

            foreach (var item in findElement)
            {
                Console.WriteLine("Find element {0} at index {1}",item.Value, item.Key);
            }

            Console.ReadLine();
        }
    }
}

output:- Find element 10 at index 6



No comments:

Post a Comment