Skip to Main Content

Binary Search: Searching last & first Element

User_AYF65Apr 19 2016 — edited Apr 27 2016

Hi,

I have coded Binary Search in java but its returning -1 when i am trying to search last or first element. If first works then last doesnt work & if last works first doesnt work. My code is given below:

import javax.swing.*;

public class BinarySearch{

   int[ ] Array = new int[10];

   BinarySearch(int[ ] a ) {

      Array = a;

   }

   int BinarySearchAlg(int num, int first, int last ) {

      int index=-1;

     

      if(first < last) {

          int mid = first + ((last - first) / 2);

          //int mid = (first + last)/2;

  JOptionPane.showMessageDialog(null, "mid= " + mid);

          if(num == Array[mid])

             index = mid;

          else if(num < Array[mid])

             index = BinarySearchAlg(num, first, mid-1);

          else

        index = BinarySearchAlg(num, mid+1, last);

       }

       return index;

   }

   public static void main(String[ ] args) {

  

      int[ ] a = {1, 12, 19, 56, 100, 134, 145, 178, 199, 201};

      BinarySearch obj = new BinarySearch(a);

      int index=obj.BinarySearchAlg(1, 1, 10);

      //int index=obj.BinarySearchAlg(201, 0, 9);

      JOptionPane.showMessageDialog(null, "index= " + index);

 

   }

}

When i tried the following statement:

int index=obj.BinarySearchAlg(1, 1, 10);

it returns -1 (i.e it cant search 1 in the array

& when i tried:

int index=obj.BinarySearchAlg(201, 0, 9);

it returns -1(i.e. it cant search 201 in the array.


Somebody please guide me.


Zulfi.

This post has been answered by User_AYF65 on Apr 20 2016
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on May 25 2016
Added on Apr 19 2016
6 comments
1,620 views