Advertisement
Venciity

[ Telerik C#] MultidimArrays 04-LowerBound

Feb 28th, 2014
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Swap(int[] arr, int i, int j)
  6.     {
  7.         int t = arr[i];
  8.         arr[i] = arr[j];
  9.         arr[j] = t;
  10.     }
  11.  
  12.     static int Partition(int[] arr, int l, int r)
  13.     {
  14.         Swap(arr, new Random().Next(l, r + 1), r);
  15.         int pivot = arr[r], i = l;
  16.  
  17.         for (int j = l; j < r; j++) if (arr[j] <= pivot) Swap(arr, i++, j);
  18.         Swap(arr, i, r);
  19.  
  20.         return i;
  21.     }
  22.  
  23.     static void QuickSort(int[] arr, int l, int r)
  24.     {
  25.         if (l >= r) return;
  26.  
  27.         int q = Partition(arr, l, r);
  28.  
  29.         QuickSort(arr, l, q - 1);
  30.         QuickSort(arr, q + 1, r);
  31.     }
  32.  
  33.     static int LowerBound(int[] arr, int x)
  34.     {
  35.         int l = 0, r = arr.Length - 1;
  36.  
  37.         while (l < r)
  38.         {
  39.             int m = l + (r - l + 1) / 2;
  40.  
  41.             if (arr[m] > x) r = m - 1;
  42.             else l = m;
  43.         }
  44.  
  45.         if (arr[l] > x) l--;
  46.  
  47.         return l;
  48.     }
  49.  
  50.     static void Main()
  51.     {
  52.         // Input
  53.         int[] arr = new int[int.Parse(Console.ReadLine())];
  54.         int k = int.Parse(Console.ReadLine());
  55.         for (int i = 0; i < arr.Length; i++) arr[i] = int.Parse(Console.ReadLine());
  56.  
  57.         // Sort
  58.         QuickSort(arr, 0, arr.Length - 1);
  59.         for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + (i == arr.Length - 1 ? "\n" : " "));
  60.  
  61.         // Search
  62.         int index = LowerBound(arr, k);
  63.  
  64.         // Print
  65.         Console.WriteLine(index);
  66.         if (index != -1) Console.WriteLine(arr[index]);
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement