Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  BidirectionBoyerMoore
Language: JAVA
Code:

public class BidirectionBoyerMoore {



     /**
      * The search method returns -1 if the string is not found, and
      * returns the location of the of the string otherwise.
      *
      *  For example, if you search for khaleel, the result will be : 6
      *
      */

     public static void main(String[] args) {
          String original = "muath khaleel mussa mahasnah";
          String text = "mahasnah";
          int index = search(original, text);
          System.out.println(index);
     }


     public static int search(String org, String text) {
          int index = -1;

          if(text.length() > org.length()) {
               return -1;
          }

          // startOrg and endOrg : The variables relating to the original string
          int startOrg = 0;
          int endOrg = text.length() - 1;

          // Variables related to the string to be searched
          int startSearch = 0;
          int endSearch = 0;

          int startIndex = 0;

          char endCharOrg = org.charAt(endOrg);
          char endCharSearch = text.charAt(endSearch);
          char startCharOrg = org.charAt(startOrg);
          char startChartSearch = text.charAt(startSearch);

          int matchCount = 0;

          startSearch = startIndex = 0;
          int loopCounter = 0;

          /**
           * The Main Loop that start searching from the main index.
           */
          while (startIndex + text.length()  <= org.length()) {

               if (matchCount >= text.length()) {
                    index = startIndex;
                    break;
               } else if(loopCounter != 0) {
                    startOrg = startOrg + 1;
                    startIndex = startOrg;
                    endOrg = startOrg + text.length() - 1;
                    startSearch = 0;
                    endSearch = text.length() - 1;
                    matchCount = 0;
               }


               /**
                * Start working from both directions.
                */
               while(startOrg <= endOrg) {
                    endCharOrg = org.charAt(endOrg);
                    endCharSearch = text.charAt(endSearch);
                    startCharOrg = org.charAt(startOrg);
                    startChartSearch = text.charAt(startSearch);

                    if(endCharOrg == endCharSearch && startCharOrg == startChartSearch) {
                         matchCount = matchCount + 2;
                         endOrg = endOrg - 1;
                         endSearch = endSearch -1;
                         startOrg = startOrg + 1;
                         startSearch = startSearch + 1;
                    } else {
                         break;
                    }
               }

               loopCounter++;
          }

          return index;
     }

}
Comments: