Question

I'm trying to make a recursive binary search that checks whether or not the words in...

I'm trying to make a recursive binary search that checks whether or not the words in a file are correct by comparing it to a dictionary file, but for some reason the method I'm using below is not working and is outputting all the words in the file I am checking as incorrect. (the dictionary is organized in alphabetical order however the file "oliver.txt" is not)

my question is what do I have to do to make this work?


public static int binarySpellcheck(String []dictionary,String [] file,int low,int high,int index){

int mid = (low+high)/2;
int key = chartoInt(file[i]);/*converts the string to its numerical value
equivalent */

if (low>high){
System.out.println("Couldn't find this word chief: "+file[i]);

incorrectWords++;
return -1;//not on the list
}//if
  
if(chartoInt(dictionary[mid])== key){
System.out.println("We found this word chief"+(dictionary[mid]));
correctWords++;
return mid;
}else if(chartoInt(dictionary[mid]) > key){
  
return binarySpellcheck(dictionary,file,low,mid-1,i);
  
}else
  
return binarySpellcheck(dictionary,file,mid+1,high,i);
  
}//binarySpellcheck

public static int chartoInt(String x){//returns the numerical sum of a word (ASCII)
String[]wordArray= new String [x.toCharArray().length];
int wordSum=0;
for (int i = 0; i < wordArray.length; i++) {
wordSum+=(int)x.toCharArray()[i];

}
return wordSum;
}

incorrectWords and correctWords are defined early in the program as global variables


the programming language is java
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1.CODE->

public class BinarySearchString {
  
   public static int incorrectWords=0;
   public static int correctWords=0;
  
  
   public static int binarySpellcheck(String[] dictionary,String[] file, int low, int high ,int index)
   {
       if(low>high) //base case to terminate recursion
       {
           incorrectWords++;
           System.out.println("Couldn't find this word chief : "+file[index]);
           return -1;
       }
      
       int mid = (low+high)/2; //middle index
      
       int res = file[index].compareTo(dictionary[mid]); // compareTo method returns either a positive or negative number or zero depending on the 2 strings
      
       if(res==0) // res==0 indicates both strings are same or equal
       {
           correctWords++;
           System.out.println("We found this word chief : "+(dictionary[mid]));
           return mid;
       }
      
       else if(res>0) //res>0 indicates that string dicitionary[mid] lexicographically less than the string file[index].
       return binarySpellcheck(dictionary,file,mid+1,high,index);
      
       else
           return binarySpellcheck(dictionary,file,low,mid-1,index); //res<0 indicates that string dicitionary[mid] lexicographically greater than the string file[index].
          
      
   }
  
     
  
   public static void main(String[] args)
   {
       String dictionary[]= {"apple","ball","cat","dog","eye"};
       String file[]= {"ant","bat","cat"};
      
       for(int i=0;i<file.length;i++)
           binarySpellcheck(dictionary,file,0,dictionary.length-1,i);
      
       System.out.println("Number of correct words : "+correctWords);
       System.out.println("Number of incorrect words : "+incorrectWords);
   }

}

2.OUTPUT->

WORKING OF COMPARE TO METHOD()->

The value 0 if the argument is a string lexicographically equal to this string. a value less than 0 if the argument is a string lexicographically greater than this string. and a value greater than 0 if the argument is a string lexicographically less than this string.

PROBLEM WITH YOUR CODE ->

previously you are using a function which is giving you the sum of ASCII values of the characters of a string.

this can lead to problem , when 2 strings have sum it will always show positive result.

Consider this scenario ->

Dictionary array contains "ant" but not contains "eye"

sum= a+n+t= 97+110+116=323

sum= e+y+e=101+121+101=323

The file contains "eye" and when we search that dictionary contains "eye" , it may show the positive result due to the presence of "ant" whose sum is same as "eye".

Second thing the dictionary is sorted lexographically , it does not mean that if you find character sum of all the strings then they will also be in incrasing order

For example -> ant , be are in dictionary order but sum are not in increasing order

sum for ant=323

sum for be=98+101=199

clearly they are not in sorted order and binary search can be only used for sorted data

so it is better to use compareTo method than this method , because using this method will give you ambigious results.

I HOPE YOU WILL GET IT.............YOUR RESPONSE WILL BE HIGHLY APPRECIATED

Add a comment
Know the answer?
Add Answer to:
I'm trying to make a recursive binary search that checks whether or not the words in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a Java application that implements the recursive Binary Search alogrithm below: Write a Java application...

    Write a Java application that implements the recursive Binary Search alogrithm below: Write a Java application that implements the recursive Binary Search alogrithm below:/** * Performs the standard binary search using two comparisons * per level. This is a driver that calls the recursive method * @return index where item is found or NOT FOUND if not found */public static <AnyType extends Comparable<? super AnyType>> int binarySearch(AnyType [] a, AnyType x) {return binarySearch(a, x, 0, a.length -1);}/** * Hidden recursive...

  • Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Wr...

    Trying to practice this assignment Argument list: the *yahoonews.txt Data file: yahoonews.txt Write a program named WordCount.java, in this program, implement two static methods as specified below: public static int countWord(Sting word, String str) this method counts the number of occurrence of the word in the String (str) public static int countWord(String word, File file) This method counts the number of occurrence of the word in the file. Ignore case in the word. Possible punctuation and symbals in the file...

  • plz solve Modify binary search so that it always returns the element with the smallest index...

    plz solve Modify binary search so that it always returns the element with the smallest index * that matches the search element (and still guarantees logarithmic running time). import java.util.Arrays; public class BinarySearch2 { public static int rank(int key, int[] a) { // Array must be sorted. int lo = 0; int hi = a.length - 1; while (lo <= hi) { // Key is in a[lo..hi] or not present. int mid = lo + (hi - lo) / 2;...

  • Modification of original code so it can include 1) at least one array 2)*New English words...

    Modification of original code so it can include 1) at least one array 2)*New English words that are written/saved to the .txt file(s) must be in alphabetical order* (e.g, Apple cannot be in a lower line than Orange). This is what I'm really struggling with as I don't know how to organize alphabetically only the english word translation without the spanish equivalent word also getting organized. The only idea I have right now is to recreate the code using two...

  • write a program which include a class containing an array of words (strings).The program will search...

    write a program which include a class containing an array of words (strings).The program will search the array for a specific word. if it finds the word:it will return a true value.if the array does not contain the word. it will return a false value. enhancements: make the array off words dynamic, so that the use is prompter to enter the list of words. make the word searcher for dynamic, so that a different word can be searched for each...

  • Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This...

    Complete the code: package hw4; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.Scanner; /* * This class is used by: * 1. FindSpacing.java * 2. FindSpacingDriver.java * 3. WordGame.java * 4. WordGameDriver.java */ public class WordGameHelperClass { /* * Returns true if an only the string s * is equal to one of the strings in dict. * Assumes dict is in alphabetical order. */ public static boolean inDictionary(String [] dict, String s) { // TODO Implement using binary search...

  • Java Im doing a binary search on an array and need to allow as many queries...

    Java Im doing a binary search on an array and need to allow as many queries as possible and cannot figure out how to. The output should read something like this. Enter a number. 3 3 is a prime number. Enter another number. 4 4 is not a prime number. Enter another number. 8 Current file not large enough for 8. Enter another number. -1 Bye. My code so far looks like this. public static void main(String[] args)    {...

  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • Why are obj1 and obj2 printing the same areas? I'm trying to learn about Comparable interface....

    Why are obj1 and obj2 printing the same areas? I'm trying to learn about Comparable interface. Couldn't figure it out. the compare to method should print 0, 1, or -1 import java.util.*; public class RectangleMain {    public static void main(String [] args) throws CloneNotSupportedException    {        /*ComparableRectangleAlsoCloneable obj1 = new ComparableRectangleAlsoCloneable(4, 5);        ComparableRectangleAlsoCloneable obj2 = (ComparableRectangleAlsoCloneable)obj1.clone();               System.out.println(obj1.toString());        System.out.println(obj1 == obj2); //false        System.out.println(obj2.toString());*/               Scanner...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT