Advertisement
stak441

MultidimensionalArrays - problem 4

Jan 15th, 2013
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace _04.BinarySearch
  7. {
  8.     class BinSearch
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             //int[] array = { 3, 8, 12, 2, 6, 5 };          //Use this for testing purposes
  13.             //int k = 16;
  14.             //int n = array.Length;
  15.  
  16.             Console.WriteLine("Please enter size N for the array and number to search:");
  17.             int n = int.Parse(Console.ReadLine());
  18.             int k = int.Parse(Console.ReadLine());
  19.             int[] array = new int[n];
  20.  
  21.  
  22.             Console.WriteLine("Enter numbers for the array:");
  23.             for (int i = 0; i < n; i++)
  24.             {
  25.                 array[i] = int.Parse(Console.ReadLine());
  26.             }
  27.  
  28.             Array.Sort(array);
  29.  
  30.             int index = Array.BinarySearch(array, k);
  31.             Console.WriteLine(index);
  32.             if (index >= 0)
  33.             {
  34.                 Console.WriteLine("The largest number that is <= {0} is {1}", k, k);
  35.             }
  36.             else if (index < 0)
  37.             {
  38.                 if (~index >= array.Length)         //This means all numbers are smaller than K, so we take the last
  39.                 {
  40.                     Console.WriteLine("The largest number that is <= {0} is {1}", k, array[n - 1]);
  41.                 }
  42.                 else if (~index == 0)                
  43.                 {
  44.                     Console.WriteLine("No numbers are <= {0}", k);
  45.                 }
  46.                 else                         // ~index will show the next largest number, so we substract 1 from it
  47.                 {
  48.                     Console.WriteLine("The largest number that is <= {0} is {1}", k, array[~index - 1]);
  49.                 }
  50.             }
  51.  
  52.            
  53.  
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement