Advertisement
stoianpp

arrays11

Dec 14th, 2013
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. // Write a program that finds the index of given element in a sorted array
  2. // of integers by using the binary search algorithm (find it in Wikipedia).
  3.  
  4. using System;
  5. class BinarySearch
  6. {
  7.     static void Main()
  8.     {
  9.         Console.Write("Enter the array length: ");
  10.         int length = int.Parse(Console.ReadLine());
  11.         Console.Write("Enter the element to be found: ");
  12.         int element = int.Parse(Console.ReadLine());
  13.         int[] myArray = new int[length];
  14.         for (int i = 0; i < length; i++)
  15.         {
  16.             Console.Write("Enter the Array1 Element[{0}]: ", i + 1);
  17.             myArray[i] = int.Parse(Console.ReadLine());
  18.         }
  19.         int minValue = 0;
  20.         int maxValue = myArray.Length;
  21.         Array.Sort(myArray);
  22.         BinarySearchMeth(minValue, maxValue, myArray, element);
  23.  
  24.     }
  25.     static void BinarySearchMeth (int min, int max, int[] Array, int elementF)
  26.     {
  27.         int pivot = min/2 + max/2;
  28.         if (Array[pivot] > elementF) max = pivot;
  29.         else if (Array[pivot] < elementF) min = pivot;
  30.         else if (Array[pivot] == elementF)
  31.         {
  32.             Console.WriteLine("The element has index {0} in the array", pivot);
  33.             return;
  34.         }
  35.        
  36.         if (min == max)
  37.         {
  38.             Console.WriteLine("There is no such element in the array");
  39.             return;
  40.         }
  41.  
  42.         if (min != max) BinarySearchMeth(min, max, Array, elementF);
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement