ellapt

T8.4.LargestNumLessK

Jan 17th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. using System;
  2.  
  3. class LargestNumLessK
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine("Read and sort an array of N integers,\nand an integer K, and using the method Array.BinSearch()\nfind the largest number in the array which is ≤ K");
  8. Console.Write("Enter the array size N: ");
  9. int n = int.Parse(Console.ReadLine());
  10. Console.WriteLine("Enter an integer number K: ");
  11. int k = int.Parse(Console.ReadLine());
  12. int[] arr = new int[n];
  13. Console.WriteLine("Enter the elements of the array: ");
  14. for (int i = 0; i < n; i++)
  15. {
  16. arr[i] = int.Parse(Console.ReadLine());
  17. }
  18.  
  19. /* int k = -4;
  20. int[] arr = {5,10,0,34,-2}; */
  21.  
  22. Array.Sort(arr);
  23.  
  24. if (k < arr[0])
  25. {
  26. Console.WriteLine("There is not any array element <= {0}", k);
  27. }
  28. else
  29. {
  30. int target = k;
  31. int index = 0;
  32. do
  33. {
  34. if (((index = Array.BinarySearch(arr, target)) >= 0))
  35. {
  36. Console.WriteLine("The largest number which is <=K is equal to {0}", target);
  37. break;
  38. }
  39. else
  40. {
  41. if (target > arr[0])
  42. {
  43. target--;
  44. }
  45. else
  46. {
  47. Console.WriteLine("There is not any array element <= {0}", k);
  48. break;
  49. }
  50. }
  51. } while (true);
  52. }
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment