Venciity

[C#] Домашно Arrays - 11 Задача

Jan 8th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 KB | None | 0 0
  1. /* Write a program that finds the index of
  2.  * given element in a sorted array of integers
  3.  * by using the binary search algorithm (find it in Wikipedia).
  4.  */
  5.  
  6. using System;
  7.  
  8. class BinarySearch
  9. {
  10.     static int BinSearch(int[] array, int key)
  11.     {
  12.         Array.Sort(array);
  13.         int iMax = array.Length - 1;
  14.         int iMin = 0;
  15.         while (iMax >= iMin)
  16.         {
  17.             int iMidpoint = (iMin + iMax) / 2;
  18.             if (array[iMidpoint] < key)
  19.             {
  20.                 iMin = iMidpoint + 1;
  21.             }
  22.             else if (array[iMidpoint] > key)
  23.             {
  24.                 iMax = iMidpoint - 1;
  25.             }
  26.             else
  27.             {
  28.                 return iMidpoint;
  29.             }
  30.         }
  31.         return -1;
  32.     }
  33.     static void Main()
  34.     {
  35.         Console.Write("Enter array length: ");
  36.         int length = int.Parse(Console.ReadLine());
  37.         int[] myArray = new int[length];
  38.  
  39.         //enter array elements
  40.         for (int i = 0; i < myArray.Length; i++)
  41.         {
  42.             Console.Write("Number {0} = ", i + 1);
  43.             myArray[i] = int.Parse(Console.ReadLine());
  44.         }
  45.         Console.Write("Key = ");
  46.         int key = int.Parse(Console.ReadLine());
  47.  
  48.         Console.WriteLine("The array is sorted ! Example : 0,1,2,3,4,6,9,20...");
  49.  
  50.         Console.Write("Index of key = ");
  51.         Console.WriteLine(BinSearch(myArray, key));
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment