Advertisement
Aborigenius

BinarySearch

Jul 5th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 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 Taks2
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             int[] uniqueInts = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
  14.             int searchElement = int.Parse(Console.ReadLine());
  15.  
  16.             int linearResult = LinearSearch(uniqueInts, searchElement);
  17.  
  18.             int[] binaryArray = uniqueInts.ToArray();
  19.  
  20.             Array.Sort(binaryArray);
  21.  
  22.             int binaryResult = BinarySearch(binaryArray, searchElement);
  23.             if (linearResult > 0)
  24.             {
  25.                 Console.WriteLine("Yes");
  26.                 Console.WriteLine($"Linear search made {linearResult + 1} iterations");
  27.                 Console.WriteLine($"Binary search made {binaryResult} iterations");
  28.             }
  29.             else
  30.             {
  31.                 Console.WriteLine("No");
  32.                 Console.WriteLine($"Linear search made {uniqueInts.Length} iterations");
  33.                 Console.WriteLine($"Binary search made {binaryResult} iterations");
  34.             }
  35.  
  36.  
  37.         }
  38.  
  39.         static int LinearSearch(int[] uniqueInts, int searchElement)
  40.         {
  41.             for (int i = 0; i < uniqueInts.Length; i++)
  42.             {
  43.                 if (uniqueInts[i] == searchElement)
  44.                 {
  45.                     return i;
  46.                 }
  47.             }
  48.             return -1;
  49.         }
  50.         public static int BinarySearch(int[] binaryArray, int searchElement)
  51.         {
  52.             int min = 0;
  53.             int max = binaryArray.Length-1;
  54.             int count = 0;
  55.             do
  56.             {
  57.                 count++;
  58.                 int mid = (min + max) / 2;
  59.                 if (binaryArray[mid] < searchElement)
  60.                     min = mid + 1;
  61.                 else
  62.                     max = mid - 1;
  63.                 if (binaryArray[mid] == searchElement)
  64.                     return count;
  65.                 //if (min > max)
  66.                 //   break;
  67.             } while (min <= max);
  68.             return count;
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement