zornitza_gencheva

Array.BinarySearch

Aug 4th, 2013
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ArrayBinSearch
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. //Task 4: Write a program, that reads from the console an array of N integers and an integer K,
  14. //sorts the array and using the method Array.BinSearch() finds the largest number in the array which is ≤ K.
  15.  
  16. Console.WriteLine("Please enter 'N' number: ");
  17. int N = int.Parse(Console.ReadLine());
  18. Console.WriteLine("Please enter 'K' number: ");
  19. int K = int.Parse(Console.ReadLine());
  20. List<int> array = new List<int>();
  21.  
  22. for (int i = 0; i < N; i++)
  23. {
  24. Console.WriteLine("Please enter {0} number of the array: ", i + 1);
  25. array.Add(int.Parse(Console.ReadLine()));
  26. }
  27.  
  28. array.Sort();
  29.  
  30. int index = array.BinarySearch(K);
  31.  
  32. if (index > 0) //The 'K' is found in the array;
  33. {
  34. Console.WriteLine("The element {0} to search for is at index {1}.", K, index);
  35. return;
  36. }
  37. else
  38. {
  39. array.Add(K); //Insert the 'K' in array;
  40. array.Sort();
  41. }
  42.  
  43. int indexK = array.IndexOf(K); //Find the index of 'K' in the array;
  44.  
  45. 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'.
  46. {
  47.  
  48. Console.WriteLine("The element {0} to search for is not found. The next larger element is {1}.", K, array[indexK - 1]);
  49. }
  50.  
  51. 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.
  52. {
  53. Console.WriteLine("No such number found.");
  54. }
  55. }
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment