Binary Search


SUBMITTED BY: Guest

DATE: Aug. 29, 2014, 5:19 p.m.

FORMAT: Bash

SIZE: 1.4 kB

HITS: 11591

  1. using System;
  2. namespace BinarySearch
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. int[] a = new int[] { 2, 4, 6, 8, 9 };
  9. Console.WriteLine(BinarySearchIterative(a, 9));
  10. Console.WriteLine(BinarySearchRecursive(a, 9, 0, a.Length));
  11. }
  12. private static int BinarySearchIterative(int[] a, int val){
  13. int low = 0;
  14. int high = a.Length;
  15. while (low <= high)
  16. {
  17. int mid = (low + high) / 2;
  18. if (a[mid] > val)
  19. high = mid-1;
  20. else if (a[mid] < val)
  21. low = mid+1;
  22. else
  23. return mid;
  24. }
  25. return -1;
  26. }
  27. private static int BinarySearchRecursive(int[] a, int val, int low, int high)
  28. {
  29. if (high < low)
  30. return -1;
  31. int mid = (low + high) / 2;
  32. if (a[mid] > val)
  33. return BinarySearchRecursive(a, val, low, mid - 1);
  34. else if (a[mid] < val)
  35. return BinarySearchRecursive(a, val, mid + 1, high);
  36. else
  37. return mid;
  38. }
  39. }
  40. }

comments powered by Disqus