Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ArrayBinSearch
- {
- class Program
- {
- static void Main(string[] args)
- {
- //Task 4: 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.
- Console.WriteLine("Please enter 'N' number: ");
- int N = int.Parse(Console.ReadLine());
- Console.WriteLine("Please enter 'K' number: ");
- int K = int.Parse(Console.ReadLine());
- List<int> array = new List<int>();
- for (int i = 0; i < N; i++)
- {
- Console.WriteLine("Please enter {0} number of the array: ", i + 1);
- array.Add(int.Parse(Console.ReadLine()));
- }
- array.Sort();
- int index = array.BinarySearch(K);
- if (index > 0) //The 'K' is found in the array;
- {
- Console.WriteLine("The element {0} to search for is at index {1}.", K, index);
- return;
- }
- else
- {
- array.Add(K); //Insert the 'K' in array;
- array.Sort();
- }
- int indexK = array.IndexOf(K); //Find the index of 'K' in the array;
- if ((K <= array[N]) && (K > array[0])) //The 'K' is not found in the array, but I put it in array, sort array again and print the number before 'K'.
- {
- Console.WriteLine("The element {0} to search for is not found. The next larger element is {1}.", K, array[indexK - 1]);
- }
- if (K == array[0]) //Print the index of number after 'K' if it is small of anyone else. If the 'K' exist it place will be before all numbers.
- {
- Console.WriteLine("No such number found.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment