aleahim

ArrayBinSearchProblem

Jan 30th, 2013
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.25 KB | None | 0 0
  1. using System;
  2.  
  3. class ArrayBinSearchProblem
  4. {
  5.     static void Main()
  6.     {
  7.         int n = int.Parse(Console.ReadLine());
  8.         int k = int.Parse(Console.ReadLine());
  9.         int[] arr = new int[n];
  10.         int temp = 0;
  11.         int min = 0;
  12.         int answerIs;
  13.  
  14.         for (int i = 0; i < n; i++)
  15.         {
  16.             arr[i] = int.Parse(Console.ReadLine());
  17.         }
  18.  
  19.         for (int j = 0; j < arr.Length - 1; j++)
  20.         {
  21.             min = j;
  22.             for (int m = j + 1; m < arr.Length; m++)
  23.             {
  24.                 if (arr[m] < arr[min])
  25.                 {
  26.                     min = m;
  27.                 }
  28.             }
  29.             if (j != min)
  30.             {
  31.                 temp = arr[j];
  32.                 arr[j] = arr[min];
  33.                 arr[min] = temp;
  34.             }
  35.         }
  36.  
  37.         if (arr[0] > k) Console.WriteLine("There is no number that is less than or equal to k");
  38.         else
  39.         {
  40.             int IndexOfElement = Array.BinarySearch(arr, k);
  41.             if (IndexOfElement >= 0) answerIs = arr[IndexOfElement];
  42.             else answerIs = arr[~IndexOfElement - 1];
  43.             Console.WriteLine("K is {0} and the number in this array which's <= K is {1}",k , answerIs);
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment