Filip13

binary_search

Sep 18th, 2024
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | Source Code | 0 0
  1. namespace binary_search
  2. {
  3.     internal class Program
  4.     {
  5.  
  6.         static void Main(string[] args)
  7.         {
  8.             int[] array = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
  9.             int target = 8;
  10.  
  11.  
  12.             int itterativePos = ItterativeBinarySearch(array, target);
  13.             Console.WriteLine(itterativePos);
  14.  
  15.             int recursivePos = RecursiveBinarySearch(array, target);
  16.             Console.WriteLine(recursivePos);
  17.         }
  18.  
  19.         private static int RecursiveBinarySearch(int[] array, int target)
  20.         {
  21.             int l = 0, r = array.Length - 1;
  22.  
  23.             return RecursiveBinarySearch(array, target, l, r);
  24.         }
  25.  
  26.         private static int RecursiveBinarySearch(int[] array, int target, int l, int r)
  27.         {
  28.             int m = (l + r) / 2;
  29.  
  30.             if (l > r)
  31.             {
  32.                 return -1;
  33.             }
  34.  
  35.             if (array[m] == target)
  36.             {
  37.                 return m;
  38.             }
  39.             if (array[m] > target)
  40.             {
  41.                 r = --m;
  42.             }
  43.             if (array[m] < target)
  44.             {
  45.                 l = ++m;
  46.             }
  47.  
  48.             return RecursiveBinarySearch(array, target, l, r);
  49.         }
  50.  
  51.         private static int ItterativeBinarySearch(int[] array, int target)
  52.         {
  53.             int l = 0, r = array.Length - 1;
  54.  
  55.             while (l <= r)
  56.             {
  57.                 int m = (l + r) / 2;
  58.  
  59.                 if (array[m] == target)
  60.                 {
  61.                     return m;
  62.                 }
  63.  
  64.                 else if (array[m] > target)
  65.                 {
  66.                     r = --m;
  67.                 }
  68.                 else// if (array[m] < target)
  69.                 {
  70.                     l = ++m;
  71.                 }
  72.             }
  73.  
  74.             return -1;
  75.         }
  76.  
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment