Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Binary search programming in C#


  1. using System;
  2.  
  3. namespace forgetCode
  4. {
  5. class Program
  6. {
  7. public static void Main()
  8. {
  9. int[] a = new int[100];
  10. Console.WriteLine("Number of elements in the array ?");
  11. string s = Console.ReadLine();
  12. int x = Int32.Parse(s);
  13. Console.WriteLine("-----------------------");
  14. Console.WriteLine(" Enter array elements ");
  15. Console.WriteLine("-----------------------");
  16. for (int i = 0; i < x; i++)
  17. {
  18. string s1 = Console.ReadLine();
  19. a[i] = Int32.Parse(s1);
  20. }
  21. Console.WriteLine("--------------------");
  22. Console.WriteLine("Enter Search element");
  23. Console.WriteLine("--------------------");
  24. string s3 = Console.ReadLine();
  25. int x2 = Int32.Parse(s3);
  26. int low = 0;
  27. int high = x - 1;
  28. while (low <= high)
  29. {
  30. int mid = (low + high) / 2;
  31. if (x2 < a[mid])
  32. high = mid - 1;
  33. else if (x2 > a[mid])
  34. low = mid + 1;
  35. else if (x2 == a[mid])
  36. {
  37. Console.WriteLine("-----------------");
  38. Console.WriteLine("Search successful");
  39. Console.WriteLine("-----------------");
  40. Console.WriteLine("Element {0} found at location {1}\n", x2, mid + 1);
  41. return;
  42. }
  43. }
  44. Console.WriteLine("Search unsuccessful");
  45. }
  46. }
  47. }


Output:

Number of elements in the array ?
4
-----------------------
Enter array elements
-----------------------
23
34
56
66
--------------------
Enter Search element
--------------------
56
-----------------
Search successful
-----------------
Element 56 found at location 3

..