ellapt

T7.11.BinarySearch

Jan 15th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class BinarySearch
  5. {
  6. static void Main()
  7. {
  8. string inputVar;
  9. uint n;
  10. Console.WriteLine("Find the index of given element in a sorted array of integers by using the binary search algorithm ");
  11. do
  12. {
  13. Console.Write("Enter array length: ");
  14. }
  15. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  16.  
  17. int[] arrayOfints = new int[n];
  18.  
  19. Console.WriteLine("Enter the elements of the array:");
  20. for (int i = 0; i < n; i++)
  21. {
  22. arrayOfints[i] = int.Parse(Console.ReadLine());
  23. }
  24.  
  25. Array.Sort(arrayOfints);
  26.  
  27. Console.WriteLine("Enter the search value:");
  28. int sVal = int.Parse(Console.ReadLine());
  29.  
  30. uint sMin = 0;
  31. uint sMax = n;
  32. uint sMid = 0;
  33.  
  34. if (sVal < arrayOfints[0] || sVal > arrayOfints[n - 1])
  35. {
  36. Console.WriteLine("Search value not found.");
  37. }
  38. else
  39. {
  40. while (sMax >= sMin)
  41. {
  42. /* the midpoint for roughly equal partition */
  43. sMid = (sMax - sMin) / 2;
  44.  
  45. // determine which subarray to search
  46. if (arrayOfints[sMid] < sVal)
  47. // change min index to search upper subarray
  48. sMin = sMid + 1;
  49. else if (arrayOfints[sMid] > sVal)
  50. // change max index to search lower subarray
  51. sMax = sMid - 1;
  52. else
  53. break;
  54. }
  55. Console.WriteLine("The index of {0} in the sorted array is: {1}", sVal, sMid);
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment