Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using the
- //method Array.BinSearch() finds the largest number in the array which is ≤ K.
- using System;
- namespace BinarySearch
- {
- class BinarySearch
- {
- static void Main()
- {
- Console.WriteLine("Please enter n.");
- int n = Int32.Parse(Console.ReadLine());
- Console.WriteLine("Please enter k.");
- int k = Int32.Parse(Console.ReadLine());
- Console.WriteLine("Please enter integers for the array - each on a new line.");
- int[] integers = new int[n];
- for (int i = 0; i < n; i++)
- {
- Console.Write("integers [{0}] = ", i);
- integers[i] = Int32.Parse(Console.ReadLine());
- Console.WriteLine();
- }
- Array.Sort(integers);
- int index = Array.BinarySearch(integers, k);
- if (index > 0)
- {
- Console.WriteLine("K is at index {0}", index);
- }
- else if (Math.Abs(index) > integers.Length)
- {
- Console.WriteLine("K is not found. The biggest number in the array is {0} at index {1}.",
- integers[integers.Length-1], integers.Length - 1);
- }
- else if (Math.Abs(index) <= integers.Length)
- {
- index = ~index;
- Console.WriteLine("K is not found. The biggest number in the array not greater than k is {0}.",
- integers[index - 1]);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement