• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

HELP

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi well I writing a program that use binarysearh and it looks an array and search for query and then say query found or not found; the program compile. however when I try to run it It shows and error saying:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 49
at InsertionSort.BinSearch(InsertionSort.java:35)
at InsertionSort.main(InsertionSort.java:21)
please help me this my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class InsertionSort
{
public static void main(String[] args) throws IOException
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
int n = 100;
int[] array = new int[args.length];
System.out.print("Enter query: ");
String s = console.readLine();
int q = Integer.parseInt(s);
// StopWatch sWatch = new StopWatch();
// sWatch.start();
int index = BinSearch(array, q, 0, n-1);
// sWatch.stop();
if (index < 0)
System.out.println("Query is not found");
else
System.out.println("Query is found at position ");

}
public static int BinSearch(int[] a, int q, int start, int finish)
{
if (start > finish) return (-1);
int mid = (start + finish) /2;
int diff = q - a[mid];
if (diff == 0)
return (mid);
else if (diff < 0)
return BinSearch(a, q, start, mid-1);
else
return BinSearch(a, q, mid+1, finish);
}
}
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jose,
Your BinSearch algorithm assumes there are 100 elements in the array. But when you declare the array as
array is the same size as however many arguments are passed in the command line when you run the program. Since you probably aren't typing in 100 numbers, this is causing the problem.
 
Danger, 10,000 volts, very electic .... tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic