Advertisement
DennyGD

BinarySearch

Feb 14th, 2015
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.67 KB | None | 0 0
  1. //Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the
  2. //method Array.BinSearch() finds the largest number in the array which is ≤ K.
  3.  
  4. using System;
  5.  
  6. namespace BinarySearch
  7. {
  8.     class BinarySearch
  9.     {
  10.         static void Main()
  11.         {
  12.             Console.WriteLine("Please enter n.");
  13.             int n = Int32.Parse(Console.ReadLine());
  14.             Console.WriteLine("Please enter k.");
  15.             int k = Int32.Parse(Console.ReadLine());
  16.             Console.WriteLine("Please enter integers for the array - each on a new line.");
  17.             int[] integers = new int[n];
  18.  
  19.             for (int i = 0; i < n; i++)
  20.             {
  21.                 Console.Write("integers [{0}] = ", i);
  22.                 integers[i] = Int32.Parse(Console.ReadLine());
  23.                 Console.WriteLine();
  24.             }
  25.  
  26.             Array.Sort(integers);
  27.  
  28.             int index = Array.BinarySearch(integers, k);
  29.             if (index > 0)
  30.             {
  31.                 Console.WriteLine("K is at index {0}", index);
  32.             }
  33.             else if (Math.Abs(index) > integers.Length)
  34.             {
  35.                 Console.WriteLine("K is not found. The biggest number in the array is {0} at index {1}.",
  36.                                     integers[integers.Length-1], integers.Length - 1);
  37.             }
  38.             else if (Math.Abs(index) <= integers.Length)
  39.             {
  40.                 index = ~index;
  41.                 Console.WriteLine("K is not found. The biggest number in the array not greater than k is {0}.",
  42.                                     integers[index - 1]);
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement