Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- namespace BinarySearchTest
- {
- class MainClass
- {
- static public int[] CutArray (int[] a, int start, int finish)
- {
- if (start < 0)
- throw new Exception ();
- if (finish > a.Length)
- throw new Exception ();
- int[] result = new int[finish - start];
- for (int i=start; i<finish; i++)
- result [i - start] = a [i];
- return result;
- }
- static public int BinarySearch (int[] sortedArray, int value)
- {
- if (sortedArray.Length == 0) {
- return -1;
- } else if (sortedArray.Length < 3) {
- for (int i=0; i<sortedArray.Length; i++)
- if (sortedArray [i] == value)
- return i;
- return -1;
- } else {
- int divider = sortedArray [sortedArray.Length / 2];
- if (divider == value)
- return sortedArray.Length / 2;
- else if (divider > value)
- return BinarySearch (CutArray (sortedArray, 0, sortedArray.Length / 2), value);
- else
- return BinarySearch (CutArray (sortedArray, sortedArray.Length / 2 + 1, 0), value);
- }
- }
- public static void Main (string[] args)
- {
- Console.WriteLine ("Hello World!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement