Advertisement
son4etyyy

SearchForK

Jan 19th, 2013
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.06 KB | None | 0 0
  1. using System;
  2. class SearchForK
  3. {
  4.     /*Write a program, that reads from the console an array of N integers and an integer K,
  5.     sorts the array and using the method Array.BinSearch()
  6.     finds the largest number in the array which is ≤ K. */
  7.     static void Main()
  8.     {
  9.         int n = int.Parse(Console.ReadLine());
  10.         int k = int.Parse(Console.ReadLine());
  11.         int[] a = new int[n];
  12.         //read the array
  13.         for (int i = 0; i < n; i++)
  14.         {
  15.             a[i] = int.Parse(Console.ReadLine());
  16.         }
  17.         //sort
  18.         Array.Sort(a);
  19.         //print the sorted array
  20.         for (int i = 0; i < n; i++)
  21.         {
  22.            Console.WriteLine(a[i]);
  23.         }
  24.         //find the index of k
  25.         int index = Array.BinarySearch(a, k);
  26.         //if (index < 0) Console.WriteLine("There is no number that is less than or equal to k.");
  27.         if (index < 0) Console.WriteLine(a[~index - 1]);
  28.         else if (index == 0) Console.WriteLine(a[index]);
  29.         else Console.WriteLine(a[index - 1]);        
  30.        
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement