Advertisement
tvarbanov

CSharp2-02-04

Dec 25th, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. using System;
  2.  
  3. class BinarySearch
  4. {
  5.     static void Main()
  6.     {
  7.         /*Write a program, that reads from the console an array of N integers and an integer K,
  8.          * sorts the array and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.*/
  9.  
  10.         Console.Write("Enter size of the array: ");
  11.         int arrSize = int.Parse(Console.ReadLine());
  12.         Console.Write("Enter the number you are looking for: ");
  13.         int number = int.Parse(Console.ReadLine());
  14.         int[] array = new int[arrSize];
  15.  
  16.         //Fill the array with elements
  17.         for (int i = 0; i < arrSize; i++)
  18.         {
  19.             array[i] = int.Parse(Console.ReadLine());
  20.         }
  21.  
  22.         //For binary search the array must be sorted
  23.         Array.Sort(array);
  24.  
  25.         //Binary Search
  26.         int index = Array.BinarySearch(array, number);
  27.         if (index > 0)
  28.         {
  29.             //If found binary search returns the index of the number
  30.             Console.WriteLine("Number {0} found at possition {1}",number,index);
  31.         }
  32.         else
  33.         {
  34.             /*if not found binary search returns the index of the nearest larger number so -1 of the index will return the greatest number
  35.              * lower thta the number we are looking for (<K)*/
  36.             index = ~index - 1;
  37.             Console.WriteLine("Largest number which is <= to {0} is {1}",number,array[index]);
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement