Advertisement
Guest User

BinarySearchMethod

a guest
Dec 29th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.31 KB | None | 0 0
  1. using System;
  2.  
  3. //Write a program, that reads from the console an array of N integers and an integer K,
  4. //sorts the array and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.
  5.  
  6. class BinarySearchMethod
  7. {
  8.     static void Main()
  9.     {
  10.         //Prepare the array
  11.         Console.Write("Enter Array's length: ");
  12.         int n = int.Parse(Console.ReadLine());
  13.         int[] array = new int[n];
  14.         for (int col = 0; col < array.Length; col++)
  15.         {
  16.             Console.Write("initilize array {0} left: ",array.Length - col);
  17.             array[col] = int.Parse(Console.ReadLine());
  18.         }
  19.         Array.Sort(array);
  20.         Console.Write("Enter K:");
  21.         int k = int.Parse(Console.ReadLine());
  22.         int indexK = Array.BinarySearch(array, k);
  23.         Console.WriteLine("Position :" + indexK);
  24.  
  25.         if (indexK < array[0])
  26.         {
  27.             Console.WriteLine("Best number: " + array[n-1]);
  28.         }
  29.         if (indexK >= 0)
  30.         {
  31.             int count = 0;
  32.             while (count < array.Length)
  33.             {
  34.                 if (array[count] == indexK)
  35.                 {
  36.                     Console.WriteLine("The best number: " + array[count+1]);
  37.                 }
  38.                     count++;
  39.  
  40.             }
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement