Advertisement
golergka

Binary Search BLIND test (not even compiled)

Jun 24th, 2012
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.19 KB | None | 0 0
  1. using System;
  2.  
  3. namespace BinarySearchTest
  4. {
  5.     class MainClass
  6.     {
  7.        
  8.         static public int[] CutArray (int[] a, int start, int finish)
  9.         {
  10.            
  11.             if (start < 0)
  12.                 throw new Exception ();
  13.             if (finish > a.Length)
  14.                 throw new Exception ();
  15.            
  16.             int[] result = new int[finish - start];
  17.            
  18.             for (int i=start; i<finish; i++)
  19.                 result [i - start] = a [i];
  20.            
  21.             return result;
  22.            
  23.         }
  24.        
  25.         static public int BinarySearch (int[] sortedArray, int value)
  26.         {
  27.            
  28.             if (sortedArray.Length == 0) {
  29.                
  30.                 return -1;
  31.                
  32.             } else if (sortedArray.Length < 3) {
  33.                
  34.                 for (int i=0; i<sortedArray.Length; i++)
  35.                     if (sortedArray [i] == value)
  36.                         return i;
  37.                
  38.                 return -1;
  39.                
  40.             } else {
  41.                
  42.                 int divider = sortedArray [sortedArray.Length / 2];
  43.                
  44.                 if (divider == value)
  45.                     return sortedArray.Length / 2;
  46.                 else if (divider > value)
  47.                     return BinarySearch (CutArray (sortedArray, 0, sortedArray.Length / 2), value);
  48.                 else
  49.                     return BinarySearch (CutArray (sortedArray, sortedArray.Length / 2 + 1, 0), value);
  50.                
  51.             }
  52.            
  53.         }
  54.        
  55.         public static void Main (string[] args)
  56.         {
  57.             Console.WriteLine ("Hello World!");
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement