Showing posts with label Searching. Show all posts
Showing posts with label Searching. Show all posts

Saturday, 18 June 2016

Program to perform Binary Search.

Code:

public class binary
{
   public static void main(String args[])
   {         int[] a = {3, 7, 10, 15, 91, 110, 150};
         int target = 91; // the element to be searched
         int left = 0;
         int middle;
         int right = a.length - 1;
         while (left < = right)
        {
              middle = (left + right) / 2;
              if (a[middle] == target)
            {
                 System.out.println("Element found at index " + middle);
                 break;
             }
             else if (a[middle] < target)
            {
                 left = middle + 1;
             }
             else if (a[middle] > target)
            {
                right = middle - 1;
             }
        }
  }
}

Program to perform Linear Search.

Code:

class linear
{
   public static void main(String args[])
   {
        int[] a = { 3, 34, 5,91, 100};
        int target = 91,flag=0;
        for( int i=0; i<a.length; i++)
       {
               if(a[i] == target)
              {
                   flag=1;
                   System.out.println ( "Element found at index "+i);
                   break;
              }
       }
       if(flag==0)  System.out.println ( "Element not found");
   }
}