Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Binary Search: Searching last & first Element

Zulfi KhanApr 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 Zulfi Khan on Apr 20 2016
Jump to Answer

Comments

James Taylor-Oracle
Not sure from your post what method you used but there is a deinstall.sh or deinstall.exe in your SOA_HOME/bin. If you are on windows you will see deinstall from the menu. This is the easiest way to deinstall.

If this fails fire up runInstaller that you used to install SOA Suite and choose to deinstall from there. You do this by selecting installed products.

cheers
James
1 - 1
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 25 2016
Added on Apr 19 2016
6 comments
1,705 views