Binary Search in C#

          Binary Search in C#


When you want to search for an element in an array, Binary Search comes into major play. 

Most common logic for Binary Search is :

1) Sort the elements in an array
2) Using Loop or Recursion, split the array in half 
3) Check for the element in the split array(either left or right). 

PseudoCode: 

  • Left =0 - Set Left index to begining of the array. 
  • Right= Length of the array. 
  • loop through the elements until left <= right 
    • calculate mid - mid = left+right/2;
    • if element we are searching is mid element, we  found the element and we exit. 
    • if element we are searching is less than the mid element, we set the right Index to mid-1 
    • if element we are searching is greater than the mid element, we set the start index to mid+1

        public static int binary_search(int[] arr, int item)
        {
            int low = 0;
            int high = arr.Length;

            while (low<=high)
            {
                int mid = (low + high) / 2;
                int guess = arr[mid];

                if(guess == item)
                {
                    return mid;
                }
                else if (guess>item )
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }

            return -1;
        }

Time Complexity : Time Complexity of Binary Search  is O(log n). 



Comments

Popular posts from this blog

Knowing too much is bad(in the world of OOP)

Reverse a LinkedList Algorithm

DateTime.Now in C#