C# Program which takes n values in an array and then program should be able to search a value in the array using binary search algorithm

Program Statement:
Write a program which takes n values in an array and then program should be able to search a value in the array using binary search algorithm. Hint: You have to sort that array first because binary search can be applied only on sorted array

Solution:
 public class search
   {
       int n, num, s = 1, e, mid;
       public void show()
       {
           Console.Write("\n\t\tEnter length of array : ");
           n = Convert.ToInt32(Console.ReadLine());
           int[] array = new int[n];
           Console.WriteLine("\n\t\tEnter {0} numbers : ", n);
           for (int i = 0; i < n; i++)
           {
               array[i] = Convert.ToInt32(Console.ReadLine());
           }
           for (int x = 0; x < n; x++)
           {
               for (int y = x + 1; y < n; y++)
               {
                   if (array[x] > array[y])
                   {
                       int temp;
                       temp = array[y];
                       array[y] = array[x];
                       array[x] = temp;
                   }
               }
           }
           Console.Write("\n\t\tEnter number to search : ");
           num = Convert.ToInt32(Console.ReadLine());
           e = n;
           mid = (s + e) / 2;
           if (num == array[mid])
           { Console.Write("\n\t\tElement {0} found!\n\n", array[mid]); }
           else if (num < array[mid])
           {
               for (int x = 0; x < mid; x++)
               {
                   if (num == array[x])
                   { Console.Write("\n\t\tElement {0} found!\n\n", array[x]); }
               }
           }
           else if (num < array[mid])
           {
               for (int y = mid; y < n; y++)
               {
                   if (num == array[y])
                   { Console.Write("\n\t\tElement {0} found!\n\n", array[y]); }
               }
           }
           else
               Console.WriteLine("\n\t\tElement not found!\n\n");
       }
   } 



Post a Comment

 
Top