Binary Search Help

Below is the coding for the binary search:
public class Binary_Search_
public int binarySearch(int arr[],int key)
int low=0;
int high=arr.length-1;
while(low<=high)
int middle=(low+high)/2;
if(key==arr[middle])
return middle;
else
if(key<arr[middle]) high=middle-1;
else low=middle+1;
return -1;//not found
The only thing is that for the binary search the array must be sorted so what could I add to the start of the coding to quickly sort the array.
You must think this is a simple question but im new to java!

Another thing..
Try rethinking your algorithm through.
int middle=(low+high)/2will not always hit the center/middle/sweet spot (or what you would call it) of your array.
If low was 2 and high was 5, your middle would be 3 (yes, 3), and if you are unlucky to have an array like this
1, 2, 3, 5, 7, 11, 13, 17, 19your code would return -1 if you were searching for 5.
And that's just one of a jillion possibilities.

Similar Messages

  • Creating A Binary search algorithm !!!! URGENT HELP

    hi ..
    i;m currently tryin to create a binary search algorithm ..
    the user should be able to input the size of the array
    and also the key that he would like to find.
    it also has to have to ability to measure the run time of the algorithm.. it how long it too the algorithm to search through the array and find they key..
    i have created 3 classes
    the first class is the binary search class
    which is the mathamatical side of things
    the second class is the Array
    this creates an array selection a random first number
    and then incrementing from there, so that its a sorted array
    the third class is the binary search class
    which is my main class.
    this class should take the users input
    and pass it to the array
    and the binary seach accordingly
    it should also measure the running time, from when it passes the array
    to the binary search class
    i am having a really hard time creating this last class.
    i have created the other 2 successfully
    the codes for the binary search class is as follows
    public class BinarySearch
         static int binSearch(int[] array, int val)
             // setting the start and the end of the array
              int low = 0, high = array.length;
              //While loop
              while(low <= high) {
              // How to find the mid point      
                  int mid = (low + high)/2;
                   // if the mid point is the value return the value
                  if(array[mid] == val) {
                        return mid;
                   // if the value is smaller than the mid point
                   // go search the left half
                   } else if(array[mid] > val) {
                        high = mid - 1;
                   //if the value is greater then the mid point
                   // go search the right half
                   } else if(array[mid] < val) {
                        low = mid + 1;
              // if value is not found return nothing
              return -1;
    }and the code for the Array class is as follows
    import java.util.Random;
    public class RandomSortedArray
        public int[] createArray(int length)
            // construct array of given length
            int[] ary = new int[length];
            // create random number generator
            Random r = new Random();
            // current element of the array; used in the loop below.  Starts at
            // -1 so that the first element of the array CAN be a 0
            int val = -1;
           for( int i = 0; i < length; i++)
                val += 1 + r.nextInt(10);
                ary[i] = val;
            return ary;
    }can some pne please help me create my binarysearchTest class.
    as i mentioned before
    it has to take the users input for the array size
    and the users input for the value that they want to find
    also needs to measure the running time
    thanks for all ur help in advance

    import java.util.*;
    public class AlgorithmTest
         public static void main(String args[])
             long StartTime, EndTime, ElapsedTime;
             System.out.println ("Testing algorithm");
             // Save the time before the algorithm run
             StartTime = System.nanoTime();
             // Run the algorithm
             SelectionSortTest1();
             // Save the time after the run
             EndTime = System.nanoTime();
             // Calculate the difference
             ElapsedTime = EndTime- StartTime;
             // Print it out
             System.out.println("The algorithm took " + ElapsedTime + "nanoseconds to run.");
        }this is the code i managed to work up for measuring the time..
    how would i include it into the main BinarysearchTest Class

  • Binary search tree help...

    Ok, maybe someone can help me with this one. Here's the code that I'm having trouble with:
      public Object findValue(Comparable aKey)
        Node result = (Node) findByKey(aKey);
        if(result != null && result.getNodeKey() == aKey)
          return result.getNodeData();
        else
          return null;
      }The problem is in the condition for the if statement, particularly, "result.getNodeKey() == aKey". I've checked both values for result.getNodeKey() and aKey, and they are both the same, but the program gives ma a false result, which sends it straight to the "return null;" statement. Any thoughts as to why it might do this?

    I just found another trouble spot. Here's the code this time:
      public boolean delete(Comparable aKey)
        Node result = (Node) findByKey(aKey);
        if(result != null && result.getNodeKey().equals(aKey))
          Node currentNode = rootNode;
          Node parentNode = null;
          boolean found = false;
          while(!found && currentNode != null)
            if(aKey.compareTo(currentNode.getNodeKey()) < 0)
              parentNode = currentNode;
              currentNode = (Node)currentNode.getLeftChild();
            else
              if(aKey.compareTo(currentNode.getNodeKey()) > 0)
                parentNode = currentNode;
                currentNode = (Node) currentNode.getRightChild();
              else
                found = true;
          if (parentNode == null)
            //here's where I need assistance
            return true;
          else
            parentNode.setLeftChild((Node) currentNode.getLeftChild());
            Node holderNode = (Node) currentNode.getLeftChild();
            holderNode.setRightChild((Node) currentNode.getRightChild());
            return true;
        else
          return false;
      }I'm trying to delete from the binary search tree, and I'm not sure how to adjust for deleting the top of the tree (rootNode, in this case) before the rest of the tree is gone. Any ideas?

  • [Help] Binary Search

    I want to do a binary search on a sorted array list.
    My question is,
    In the java.util package, there is a pre-written methods, Arrays.binarySearch() which I can use it to do the searching straight forward. What I concern here, if I write the binary search algorithm myself, will it be fastest?
    Let's assume, there are only integers in the array, and the binary search algorithm that I am going to write in traditional way that widely used today.

    Whenever there is a method available in the API we need not write the method once again. All the way whatever we write may contain some pit-falls and it may fail some where at the same it won't be that much efficient also.

  • Java question help (applying binary search)

    please show me how do i apply a binary search inside this program where i can use the binary serach to search for the book author or book title
    // objectSort.java
    // demonstrates sorting objects (uses bubble sort)
    // to run this program: C>java libmainsys
    class libary
    private String booktitle;
    private String bookauthor;
    private String publisher;
    private int yearpublished;
    private int edition;
    private int nofcop;
    public libary(String title, String author, String pub, int yrpub, int edt, int nfcp)
    {                // constructor
    booktitle = title;
    bookauthor = author;
    publisher = pub;
    yearpublished = yrpub;
    edition = edt;
    nofcop = nfcp;
    public void displaylibary()
    System.out.print(" Book Title: " + booktitle);
    System.out.print(", Book Author: " + bookauthor);
    System.out.print(", Book Publisher: " + publisher);
    System.out.print(", Year Published: " + yearpublished);
    System.out.print(", Edition: " + edition);
    System.out.println(",No Of Copies : " + nofcop);
    public String getLast() // get title
    { return booktitle; }
    } // end class libary
    class ArrayInOb
    private libary[] nfcp; // ref to array ypub
    private int nElems; // number of data items
    public ArrayInOb(int max) // constructor
    nfcp = new libary[max]; // create the array
    nElems = 0; // no items yet
    // put libary into array
    public void insert(String title, String author, String pub, int yrpub, int edt, int nofcop)
    nfcp[nElems] = new libary(title, author, pub, yrpub, edt, nofcop);
    nElems++; // increment size
    public void display() // displays array contents
    for(int j=0; j<nElems; j++) // for each element,
    nfcp[j].displaylibary(); // display it
    System.out.println("");
    public void bubbleSort()
    int i, j;
    libary temp;
    for (i = nElems-1; i >= 0; i--)
    for (j = 1; j <= i; j++)
    if (nfcp[j-1].getLast().compareTo(nfcp[j].getLast())>0)
    temp = nfcp[j-1];
    nfcp[j-1] = nfcp[j];
    nfcp[j] = temp;
    } // end class ArrayInOb
    class libmainsys
    public static void main(String[] args)
    int maxSize = 1000; // array size
    ArrayInOb arr; // reference to array
    arr = new ArrayInOb(maxSize); // create the array
    arr.insert("Java_how__to_program", "Patty_John", "Deitel", 2001, 1, 430);
    arr.insert("System_Design", "Dexter_Smith", "Thomson", 2002, 3, 450);
    arr.insert("Program_Design", "Lorraine_Paul", "About", 1996, 2, 196);
    arr.insert("Computer_Architecture", "Paul_Andrew","Dzone", 2006, 5, 199);
    arr.insert("Visual_Basic_How_To_ Program", "Tom_Jones", "Jeffereson_publication", 2007, 4, 207);
    arr.insert("Information_ Management", "William_Peter", "Mcgraw_Hill", 1995, 3, 204);
    arr.insert("Sofware_ Application", "Henry_Sam", "Pearson", 2001, 6, 278);
    arr.insert("English", "Samantha_Julia", "James_Hill", 2005, 1, 200);
    arr.insert("Web_Publishing", "Audrey_Cynthia", "Surg", 2004, 3, 201);
    arr.insert("Human_Computer_Interaction", "Tony_Edward", "Telde", 2003, 3, 199);
    System.out.println("Before sorting:");
    arr.display(); // display items
    arr.bubbleSort(); // insertion-sort them
    System.out.println("After sorting:");
    arr.display(); // display them again
    } // end main()
    } // end class libmainsys

    I see you haven't worked out bubbleSort either. Since binary search only works on sorted arrays, I suggest you start there. Do you have the algorithms somewhere?
    If you really need to be able to search using either author or title, I suggest you create 2 Comparators that compare using the desired property. Comparator is just an interface that defines methods to compare 2 objects. You have to write your own implementation of it to compare library objects. You'll always have to sort and search using the same Comparator.

  • How does sy-tabix affect by binary search transforming no fields?

    1 report ztx1110.
         2 data: begin of it occurs 3,
         3           f1(2) type n,
         4           f2    type i,
         5           f3(2) type c,
         6           f4    type p,
         7           end of it.
         8
         9   it-f1 = '40'. it-f3 = 'DD'. it-f2 = it-f4 = 4. append it.
        10  it-f1 = '20'. it-f3 = 'BB'. it-f2 = it-f4 = 2. append it.
        11
        12 sort it by f1.
        13 do 5 times.
        14     it-f1 = sy-index * 10.
        15     it-f3 = 'XX'.
        16     it-f2 = it-f4 = sy-index.
        17     read table it
        18         with key f1 = it-f1
        19         binary search
        20         transporting no fields.
        21     if sy-subrc <> 0.
        22         insert it index sy-tabix.
        23         endif.
        24     enddo.
        25
        26 loop at it.
        27     write: / it-f1, it-f2, it-f3, it-f4.
        28     endloop.
    in this program changing value of sy-tabix as such sy-index.
    means in it's first loop it's value is 1, on second loop it's 2, and so on up to 5.
    okay that is due to binary search.
    but why binary search affecting this system variable?

    Hi Vinay,
    It is simple.
    This depends on your select query. 
    CASE 1: If you use select ..into table.....,  then there wil be nothing in your header ls_vbap. Now if you execute READ stmt..you will get nothing.
    CASE 2: If you use Select..... into ls_vbap.....append ls_vbap....clear ls_vbap.....endselect.   In this case also the output of READ will be nothing because you are clearing header.  So while READ stmt you are comparing ls_vbap-vbeln and ls_vbap-posnr , as nothing in it you will get nothing
    CASE 3: If you use case 2 without CLEAR stmt then always you will get the index of the last fetched record...i.e., the last record of the internal table before sorting..
    I think it is helpful for you....if you are not clear just reply me

  • Binary Search need clarification

    Hi All,
      I am facing a problem here in binary search. I will try to explain the situation with an example.
    Internal table : it_vbap
    Fields :  vbeln   posnr   qty
    Index 1  100      10       5
    index 2  100      10       5
    index 3  100      20       5
    index 4  100      20       5
    index 5  100      30       5
    index 6  100      30      5
    the abap code is this.
    sort it_vbap by vbeln posnr.
    read table it_vbap into ls_vbap with ket
                   vbeln  = ls_vbap-vbeln
                   psonr = ls_vbap-posnr
                   binary search.
    If sy-subrc  = 0.
    write : 'index :' sy-tabix.
    endif.
    My question here is does it always write index 1,3,5 (means in the all the case it should return the first record  ), otherwise it can also return 1, 3, 6.
    Pay attendtion the posnr are the same for every two records.
    The internal table not only contains 6 six records , my question was however not depends on the number of records in the internal table, the binary search will return the first sorted key record in the table or not.
    Please post your views.
    Thanks & regards,
    Vijay

    Hi Vinay,
    It is simple.
    This depends on your select query. 
    CASE 1: If you use select ..into table.....,  then there wil be nothing in your header ls_vbap. Now if you execute READ stmt..you will get nothing.
    CASE 2: If you use Select..... into ls_vbap.....append ls_vbap....clear ls_vbap.....endselect.   In this case also the output of READ will be nothing because you are clearing header.  So while READ stmt you are comparing ls_vbap-vbeln and ls_vbap-posnr , as nothing in it you will get nothing
    CASE 3: If you use case 2 without CLEAR stmt then always you will get the index of the last fetched record...i.e., the last record of the internal table before sorting..
    I think it is helpful for you....if you are not clear just reply me

  • Search help on screen elements

    Hi I have a screen where I need to include a seach help on the screen element.  The element itself is just a generic char 8 field with no dictionary reference.  I have tried using the VRM_SET_ VALUES in the PBO but as soon as I press enter it looses the value selected. So I have now tried the using the process on value_request but despite finding and populating 138 values in the search help pop up, the actual pop up screen shows a blank list, with the text at the bottom saying 138 values.
    Any ideas what I am doing wrong?
    Set list values
        call function 'VRM_SET_VALUES'
          exporting
            id              = lv_vrm_id
            values          = it_values
          exceptions
            id_illegal_name = 1
            others          = 2.
        if sy-subrc <> 0.
       MESSAGE I000 WITH 'Failed to populate username list values'.
        endif.
    process on value-request.
      field my_field module fill_my_field.
      call function 'F4IF_INT_TABLE_VALUE_REQUEST'
        exporting
          retfield        = 'MY_FIELD
          dynprofield     = 'MY_FIELD'
          value_org       = ' '
          dynpprog        = progname
          dynpnr          = dynnum
        tables
          value_tab       = it_values "it contains 2 fields that will be shown in the list box
        exceptions
          parameter_error = 1
          no_values_found = 2
          others          = 3.

    I'm still having problems with this.  Here is my VRM set values - the problem I have with this is as soon as i choose a value from the list and press enter, the value dissappears from the screen element:
    data: lv_vrm_id(80)    type c.
        data: lv_key(3)        type n value 1,
              lv_index         type sy-tabix.
        data: it_values  type standard table of vrm_value,
              s_values   type vrm_value.
        lv_vrm_id = i_type.
        lv_key    = 1.
        clear it_values.
        loop at it_cabn into s_cabn
                        where ATNAM = i_type.
          read table it_cawn into s_cawn with key atinn = s_cabn-atinn
                                         binary search.
          while s_cawn-atinn = s_cabn-atinn.
            lv_index = sy-tabix.
            s_values-key  = 1.
            s_values-text =   s_cawn-ATWRT.
            condense s_values-text.
            append s_values to it_values.
            add 1 to lv_key.
            lv_index = lv_index + 1.
            read table it_cawn into s_cawn index lv_index.
            if sy-subrc <> 0.
              exit.
            endif.
          endwhile.
        endloop.
    * Set list values
        call function 'VRM_SET_VALUES'
          exporting
            id              = lv_vrm_id
            values          = it_values
          exceptions
            id_illegal_name = 1
            others          = 2.
        if sy-subrc <> 0.
    *    MESSAGE I000 WITH 'Failed to populate username list values'.
        endif.
    And here is my code for the F4 lookup - the problem here is that the search help pop dispklays nothing depsite saying it has 138 values.  I am wondering if its my it_values that is the wrong format, or is it the fact that my field type doesn't point to a dictionary element?
    TYPES: BEGIN OF ty_values,
               type(8),
               descr(20),
             END OF ty_values.
      DATA: it_values TYPE STANDARD TABLE OF ty_values,
            s_values  type ty_values.
      data: lv_key(3)        type n value 1,
            lv_index         type sy-tabix.
    * Build lookup values for wood type test
      clear it_values.
      loop at it_cabn into s_cabn
                      where atnam = i_type.
        read table it_cawn into s_cawn with key atinn = s_cabn-atinn
                                       binary search.
        while s_cawn-atinn = s_cabn-atinn.
          lv_index = sy-tabix.
    *      s_values-key  = 1.
    *      s_values-value1 =   s_cawn-atwrt.
          s_values-type =   s_cawn-atwrt.
          append s_values to it_values.
          lv_index = lv_index + 1.
          read table it_cawn into s_cawn index lv_index.
          if sy-subrc <> 0.
            exit.
          endif.
          add 1 to lv_key.
        endwhile.
      endloop.
    DATA: progname TYPE sy-repid,
          dynnum   TYPE sy-dynnr,
          dynpro_values TYPE TABLE OF dynpread,
          field_value LIKE LINE OF dynpro_values.
      progname = sy-repid.
      dynnum   = sy-dynnr.
      call function 'F4IF_INT_TABLE_VALUE_REQUEST'
        exporting
          retfield        = 'ATWRT'
          dynprofield     = 'TYPE'
          value_org       = ' '
          dynpprog        = progname
          dynpnr          = dynnum
        tables
          value_tab       = it_values "it contains 2 fields that will be shown in the list box
        exceptions
          parameter_error = 1
          no_values_found = 2
          others          = 3.
      if sy-subrc <> 0.
      endif.

  • Binary Search in Dynamic Read

    Here is the code
          read table <fs_it_crv> assigning <fs_wa_crv> with key
                                      ('objty') = wa_plfh-objty
                                      ('objid') = wa_plfh-objid
                                      binary search.
    If i use binary search system giving error while activating as
    You cannot use explicit or implicit index operations on tables with
    types "HASHED TABLE" or "ANY TABLE". "" has the type "ANY
    TABLE". It is possible that .
    How could i use Binary search in dynamic read

    Hello,
    how do you create your internal table "<FS_IT_CRV>" ?
    i found this thread [here|Need help regarding Dynamic Read Table statement;.
    You can try the code lines of  David Klotz.
    If you insert a sort statement before read and change read adding binary search it might work.
    SORT <gt_itab> BY (ge_key_field1) (ge_key_field2) (ge_key_field3) .
    * Finally, perform the search
      READ TABLE <gt_itab> ASSIGNING <gs_result>
              WITH KEY (ge_key_field1) = pa_cond1
                       (ge_key_field2) = pa_cond2
                       (ge_key_field3) = pa_cond3 BINARY SEARCH.
    I tried the following code in my own program and it works:
    SORT <wlf_t_data> BY (c_trkorr).
      read table <wlf_t_data> assigning <wlf_header> with key
             (c_trkorr) = 'DRR' binary search.
    Where   <wlf_t_data> is a dynamic table created by method create_dynamic_table of class cl_alv_table_create.
    Cordialement,
    Chaouki

  • Searching a binary search tree  written to a file

    hello
    I have a binary search tree which has 10 levels. Now I want to search a node
    after writing all the nodes to a file.
    Can anyone help me in doing this. A sample code would be great ...
    Thanks
    K

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • How to display our own selected data in a search help using a exit

    Hello,
    I had created a Search Help Exit to restrict the values to be displayed in the search help. This code was written under the event 'DISP' in the exit. But it is not giving the desired result. So I want to replace the RECORD_TAB of the exit with my own selected data. For this I had written code for selection under the event 'SELECT'. But when I try to overwrite RECORD_TAB with this, this create errors.
    What should I do to overwrite the values of the RECORD_TAB field with my own values?
    Regards,
    Abijith

    Hi,
    This is how we implemented the code modify the values in search help exit.
    Check if display process button is pressed
      IF callcontrol-step = 'DISP'.
    Read the parameter ID for company code.
        GET PARAMETER ID 'BUK' FIELD lv_bukrs.
        IF sy-subrc EQ 0.
          lwa_bukrs-sign   = 'I'.
          lwa_bukrs-option = 'EQ'.
          lwa_bukrs-low    = lv_bukrs.
          APPEND lwa_bukrs TO lr_bukrs.
        ENDIF.
      Check if any entry is made in Test account/Testity account name
        LOOP AT shlp-selopt INTO lwa_selopt.
          CASE lwa_selopt-shlpfield.
            WHEN  'ZZTEST'.
              lwa_roy-sign = lwa_selopt-sign.
              lwa_roy-option = lwa_selopt-option.
              lwa_roy-low = lwa_selopt-low.
              APPEND lwa_roy TO lr_roy.
            WHEN 'ZZTEST_NAME'.
              lwa_roy_name-sign = lwa_selopt-sign.
              lwa_roy_name-option = lwa_selopt-option.
              lwa_roy_name-low = lwa_selopt-low.
              APPEND lwa_roy_name TO lr_roy_name.
          ENDCASE.
        ENDLOOP.
      Get customer in entered for a company code
        SELECT kunnr
               bukrs
          FROM knb1
          INTO TABLE lt_knb1
          WHERE kunnr IN lr_roy
            AND bukrs IN lr_bukrs.
        IF sy-subrc EQ 0.
          SORT lt_knb1 BY kunnr.
        Get customer name for  the customer.
          SELECT kunnr
                 name1
            FROM kna1
            INTO TABLE lt_kna1
            FOR ALL ENTRIES IN lt_knb1
            WHERE kunnr EQ lt_knb1-kunnr
              AND mcod1   IN  lr_roy_name.
          IF sy-subrc EQ 0.
            SORT lt_kna1 BY kunnr.
          ENDIF.
        ENDIF.
      Get Values for Testty account selected by standard search help
        CALL FUNCTION 'F4UT_PARAMETER_VALUE_GET'
          EXPORTING
            parameter   = 'Ztest'
            fieldname   = 'Ztest'                                    " Reference to search help parameter
          TABLES
            shlp_tab    = shlp_tab                                    " Reference to field of Seatinfo
            record_tab  = record_tab
            results_tab = lt_test_help
          CHANGING
            shlp        = shlp
            callcontrol = callcontrol.
      Get Values for Testty account Name selected by standard search help
        CALL FUNCTION 'F4UT_PARAMETER_VALUE_GET'
          EXPORTING
            parameter   = 'Ztest1'
            fieldname   = 'Ztest1'                                    " Reference to search help parameter
          TABLES
            shlp_tab    = shlp_tab                                    " Reference to field of Seatinfo
            record_tab  = record_tab
            results_tab = lt_roy_help
          CHANGING
            shlp        = shlp
            callcontrol = callcontrol.
        LOOP AT lt_knb1 INTO lwa_knb1.
          CLEAR lwa_kna1.
          READ TABLE lt_kna1
                INTO lwa_kna1
                WITH KEY kunnr = lwa_knb1-kunnr
                BINARY SEARCH.
          IF sy-subrc EQ 0.
            CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
              EXPORTING
                input  = lwa_kna1-kunnr
              IMPORTING
                output = lv_kunnr.
            lwa_roy_help-ztest1 = lv_kunnr.
            lwa_roy_help-ztest = lwa_kna1-name1.
            APPEND lwa_roy_help TO lt_roy_help .
          ENDIF.
        ENDLOOP.
        SORT lt_ztest_help.
        DELETE ADJACENT DUPLICATES FROM lt_roy_help COMPARING ZTEST1.
    Finally transport the computed numbers into the search help data.
        CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
          EXPORTING
            parameter   = 'ZTEST1'
            fieldname   = 'ZTEST1'" Reference to search help parameter
          TABLES
            shlp_tab    = shlp_tab                                    " Reference to field of Seatinfo
            record_tab  = record_tab
            source_tab  = lt_roy_help
          CHANGING
            shlp        = shlp
            callcontrol = callcontrol.
    Finally transport the computed numbers into the search help data.
        CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
          EXPORTING
            parameter   = 'ZTEST''
            fieldname   = 'ZTEST''                                  " Reference to search help parameter
          TABLES
            shlp_tab    = shlp_tab                                    " Reference to field of Seatinfo
            record_tab  = record_tab
            source_tab  = lt_roy_help
          CHANGING
            shlp        = shlp
            callcontrol = callcontrol.
      ENDIF.
    Nabheet

  • Binary search tree - writing to a file in alphabetic order words from tree

    Hi
    I have written a program that will read a list of words from a file, insert these into a binary search tree, write words from the tree to another file, so that the resulting list contains words in ascending order. My input file Alpha1.txt contains the following contents in the order and format given (one word per line):
    Dawn
    Dave
    Mike
    Beth     
    David
    Gina
    Pat
    Cindy
    Sue
    My program is supposed to be producing an alphabetical list of these words in another file "final.txt".
    Instead it gives me the following list:
    Dave Beth David Gina Cindy Sue Pat Mike Dawn
    This is obviously wrong, right? My correct list in "final.txt" should be
    Beth Cindy Dave David Dawn Gina Mike Pat Sue
    I am not sure what is wrong with my code which I reproduce below:
    import java.io.*;
    import java.util.*;
    //read Java Developer's Almanac from exampledepot.com
    //Read this: http://en.wikipedia.org/wiki/Tree_traversal
    /**preorder(node)
      print node.value
      if node.left  ? null then preorder(node.left)
      if node.right ? null then preorder(node.right)
    public class AlphabeticBinarySortTree
         private static TreeNode root;
         private static TreeNode runner;
         static String[] alphaArray;
         static int alphaCounter;
         private static TreeNode alphaRunner;
         //Inner class
              private static class TreeNode
                   String word;
                   TreeNode left;
                   TreeNode right;
                   int count;
                   public TreeNode(String word)
                        this.word = word;
                        left = null;
                        right = null;
                   public void insertAll(TreeNode newNode)
                        if(newNode.word.compareTo(runner.word) < 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.left == null)
                                  runner.left = newNode;
                                  runner = runner.left;
                             else
                                  insertAll(newNode);
                        else if(newNode.word.compareTo(runner.word) > 1)
                             System.out.println("newNode.word = " + newNode.word);
                             if(runner.right == null)
                                  runner.right = newNode;
                                  runner = runner.right;
                             else
                                  insertAll(newNode);
                        else
                             count++;
                   }// end method insertAll
                   // Recursively print words (with counts) in sorted order
                     public static void printInPreOrder(TreeNode root)
                             System.out.println(root.word + " ");
                             if(root.left != null)
                                   printInPreOrder(root.left);
                              if(root.right != null)
                                   printInPreOrder(root.right);
                       } //end method printInPreOrder()
                     //called from inside main
                    public static void arrangeInAscendingOrder(TreeNode root, PrintWriter pWriter)
                             if(root.left != null)
                                   arrangeInAscendingOrder(root.left, pWriter);
                             System.out.println();
                             System.out.println();
                             System.out.println(root.word + " ");
                             pWriter.write(root.word + " ");
                             if(root.right != null)
                                  arrangeInAscendingOrder(root.right, pWriter);
              }//end inner class TreeNode
         public AlphabeticBinarySortTree()
              root = null;
         //belong to the outer class
         public static void main(String[] args)
              System.out.println("This program reads text from a file that it will parse. ");
              System.out.println("In doing so, it will eliminate duplicate strings and ");
              System.out.println("pick up only unique strings.These strings will be in a ");
              System.out.println("stored in alphabetical order in a binary Search tree before they are ");
              System.out.println("written out to another text file in alphabetic order");
              //open the file for reading
              try
                   BufferedReader bReader = new BufferedReader(new FileReader("Alpha1.txt"));
                   String words;
                   int count;
                   //System.out.println("A test to inspect the contents of words: " + words);
                   //System.out.println("Words =" + words);
                   count = 0;
                   //why is there an endless loop when
                   //I use "while(str != null)
                   StringTokenizer st;
                   st = null;
                   //based on http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html
                   while ((words = bReader.readLine()) != null)
                        st = new StringTokenizer(words);
                       while(st.hasMoreTokens())
                            //shiffman.net/teaching/a2z/concordance
                            String token = st.nextToken();
                            System.out.println("Token = " +token);
                            AlphabeticBinarySortTree.initiateInsert(token);
                            //count the number of tokens in the string
                            count++;
                        }//end inner while
                   }//end outer while
                   System.out.println("Here are the contents of your tree:");
                   //System.out.println("before the call to print()");
                   print();
                   System.out.println("the no of words in the file is: " + count);
                   bReader.close();
              }//end of try
              catch(IOException exception)
                   exception.printStackTrace();
                   /**try
                             FileWriter fWriter = new FileWriter("final.txt");
                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                             PrintWriter pWriter = new PrintWriter(bWriter);
                   catch(IOExcepion exception)
                        exception.printStackTrace();
         } // end main here
         //this method belongs to the outer class
         static void initiateInsert(String word)
              //TreeNode is also static by the way
              TreeNode newNode = new TreeNode(word);
              if(root == null)
                   root = newNode;
                   System.out.println("root.word = " + root.word);
                   runner = root;
              else
                   runner.insertAll(newNode);
         // Start the recursive traversing of the tree
            //without the access specifier 'static'
            //I would get the following error message
            //AlphabeticBinarySortTree.java:119: non-static method print() cannot be referenced from a static context
            public static void print()
                //System.out.println("**********AM I INSIDE THE PRINT() METHOD? ********");
               if (root != null)
                    //System.out.println("++++++++ AM I INSIDE THE IF BLOCK OF THE PRINT() METHOD? +++++++");
                    //System.out.println("Inside THE IF BLOCK OF print() BUT BEFORE THE CALL TO printInPreOrder(),root.word = " + root.word);
                  AlphabeticBinarySortTree.TreeNode.printInPreOrder(root);
                  //open the file for writing
                              try
                                             FileWriter fWriter = new FileWriter("final.txt");
                                             BufferedWriter bWriter = new BufferedWriter(fWriter);
                                             PrintWriter pWriter = new PrintWriter(bWriter);
                                             AlphabeticBinarySortTree.TreeNode.arrangeInAscendingOrder(root, pWriter);
                                          pWriter.close();
                              catch(IOException eException)
                                   eException.printStackTrace();
               }//end of if block
            } // end of method print
    }//end outer enclosing class here--------
    All help is highly appreciated. Thanks for your time and consideration.

    You suggest that I do away with the inner class
    then?Absolutely. In fact I strongly suggest this. You are learning how to code and need to do things cleanly and in small steps. That means first creating your Node class and making sure it works. Then creating your Tree class, and making sure it works. In fact I would load the Strings into the Tree class first directly and testing things before even thinking about reading to and from files. Only then should you implement the file input and output steps.
    The key here is that you don't go on to the next step until you're reasonably sure that your current code works. Remember, it's MUCH easier to code than to debug.

  • Problem with binary search tree

    Hi all, just having troubles with a program im writing.
    My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
    I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
    Here if my sell Item method:
        public void sellItem(Item item, int quantity){
            stockItem = item;
            mQuantity = quantity;
            if (tree.includes(stockItem)){
                int tempQuantity = stockItem.getQuantityInStock();
                tempQuantity -= mQuantity;
            else{
                throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
        }and here is where i am calling it in a test class :
    number1.sellItem(item1, 40);Each item is in this format :
    ABCD, PENCIL, 1, 0.35, 200, 100, 200
    where 200 is the quantity.
    Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
    below is a copy of my binary tree :
    public class BSTree extends Object {
        private class TreeNode extends Object{
            public Comparable data;
            public TreeNode left;
            public TreeNode right;
            public TreeNode() {
                this(null);
            public TreeNode(Comparable barCode){
                super();
                data = barCode;
                left = null;
                right = null;
        private TreeNode root; 
        private int nodeCount;
        public BSTree(){
            super();
            root = null;
            nodeCount = 0;
        public boolean isEmpty() {
          return root == null;
        public int size() {
          return nodeCount;
        private TreeNode attach(TreeNode newPointer, TreeNode pointer){
            if (pointer == null){
                nodeCount++;
                return newPointer;
            else {
                Comparable obj1 = (Comparable) newPointer.data;
                Comparable obj2 = (Comparable) pointer.data;
            if (obj1.compareTo(obj2) < 0) //Go left
                pointer.left = attach(newPointer, pointer.left);
            else //Go right
                pointer.right = attach(newPointer, pointer.right);
            return pointer;
        public void insert(Comparable item){
            //Create a new node and initialize
            TreeNode newPointer = new TreeNode(item);
            //Attach it to the tree
            root = attach(newPointer, root);
        public Comparable remove(Comparable key) {
            TreeNode pointer;
            TreeNode parent;
            //Find the node to be removed
            parent = null;
            pointer = root;
            while ((pointer != null) && !key.equals(pointer.data)) {
                parent = pointer;
                if (key.compareTo(pointer.data) <0)
                    pointer = pointer.left;
                else
                    pointer = pointer.right;
            if (pointer == null)
                return null;
            //Orphans
            TreeNode leftSubtree = pointer.left;
            TreeNode rightSubtree = pointer.right;
            if (parent == null)
                root = null;
            else if (key.compareTo(parent.data) < 0)
                parent.left = null;
            else
                parent.right = null;
            //Reattaching any orphans in the left subtree
            if (leftSubtree != null) {
                root = attach(leftSubtree, root);
                nodeCount--;
            //Reattaching any orphans in the right subtree
            if (rightSubtree != null) {
                root = attach(rightSubtree, root);
                nodeCount--;
            nodeCount--;
            return pointer.data;
        private TreeNode search(TreeNode pointer, Comparable key) {
            if (pointer == null)
                return null;
            else if (pointer.data.compareTo(key) == 0)
                return pointer;
            else if (key.compareTo(pointer.data) < 0)
                return search(pointer.left, key);
            else
                return search(pointer.right, key);
        public boolean includes(Comparable key) {
            return (search(root, key) != null);
        public Comparable retrieve(Comparable key) {
            TreeNode pointer;
            pointer = search(root, key);
            if (pointer == null)
                return null;
            else
                return pointer.data;
        public Comparable[] getAllInOrder() {
            Comparable[] list = new Comparable[nodeCount];
            inOrderVisit(root,list,0);
            return list;
        private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
            if (pointer != null) {
                count = inOrderVisit(pointer.left, list, count);
                list[count++] = pointer.data;
                count = inOrderVisit(pointer.right, list, count);
            return count;
        public String toString() {
            StringBuffer result = new StringBuffer(100);
            inOrderString(root, result);
            return result.toString();
        private void inOrderString(TreeNode pointer, StringBuffer result) {
            if (pointer != null) {
                inOrderString(pointer.left, result);
                result.append(pointer.data.toString() + "\n");
                inOrderString(pointer.right, result);
    }Thanks for everyones help. Keep in mind i'm very new to java.

    Hi all, just having troubles with a program im writing.
    My program is based on a binary search tree full of items which are passed in via an input file and then saved to an output file.
    I have written a sellItem method which gets passed in the item and quantity that has been sold which then needs to be changed in the binary tree.
    Here if my sell Item method:
        public void sellItem(Item item, int quantity){
            stockItem = item;
            mQuantity = quantity;
            if (tree.includes(stockItem)){
                int tempQuantity = stockItem.getQuantityInStock();
                tempQuantity -= mQuantity;
            else{
                throw new IllegalArgumentException("The Barcode " + mBarCode + " does NOT exist.");
        }and here is where i am calling it in a test class :
    number1.sellItem(item1, 40);Each item is in this format :
    ABCD, PENCIL, 1, 0.35, 200, 100, 200
    where 200 is the quantity.
    Therefore if i pass 40 into the method the binary search tree should then store the quantity as 160.
    below is a copy of my binary tree :
    public class BSTree extends Object {
        private class TreeNode extends Object{
            public Comparable data;
            public TreeNode left;
            public TreeNode right;
            public TreeNode() {
                this(null);
            public TreeNode(Comparable barCode){
                super();
                data = barCode;
                left = null;
                right = null;
        private TreeNode root; 
        private int nodeCount;
        public BSTree(){
            super();
            root = null;
            nodeCount = 0;
        public boolean isEmpty() {
          return root == null;
        public int size() {
          return nodeCount;
        private TreeNode attach(TreeNode newPointer, TreeNode pointer){
            if (pointer == null){
                nodeCount++;
                return newPointer;
            else {
                Comparable obj1 = (Comparable) newPointer.data;
                Comparable obj2 = (Comparable) pointer.data;
            if (obj1.compareTo(obj2) < 0) //Go left
                pointer.left = attach(newPointer, pointer.left);
            else //Go right
                pointer.right = attach(newPointer, pointer.right);
            return pointer;
        public void insert(Comparable item){
            //Create a new node and initialize
            TreeNode newPointer = new TreeNode(item);
            //Attach it to the tree
            root = attach(newPointer, root);
        public Comparable remove(Comparable key) {
            TreeNode pointer;
            TreeNode parent;
            //Find the node to be removed
            parent = null;
            pointer = root;
            while ((pointer != null) && !key.equals(pointer.data)) {
                parent = pointer;
                if (key.compareTo(pointer.data) <0)
                    pointer = pointer.left;
                else
                    pointer = pointer.right;
            if (pointer == null)
                return null;
            //Orphans
            TreeNode leftSubtree = pointer.left;
            TreeNode rightSubtree = pointer.right;
            if (parent == null)
                root = null;
            else if (key.compareTo(parent.data) < 0)
                parent.left = null;
            else
                parent.right = null;
            //Reattaching any orphans in the left subtree
            if (leftSubtree != null) {
                root = attach(leftSubtree, root);
                nodeCount--;
            //Reattaching any orphans in the right subtree
            if (rightSubtree != null) {
                root = attach(rightSubtree, root);
                nodeCount--;
            nodeCount--;
            return pointer.data;
        private TreeNode search(TreeNode pointer, Comparable key) {
            if (pointer == null)
                return null;
            else if (pointer.data.compareTo(key) == 0)
                return pointer;
            else if (key.compareTo(pointer.data) < 0)
                return search(pointer.left, key);
            else
                return search(pointer.right, key);
        public boolean includes(Comparable key) {
            return (search(root, key) != null);
        public Comparable retrieve(Comparable key) {
            TreeNode pointer;
            pointer = search(root, key);
            if (pointer == null)
                return null;
            else
                return pointer.data;
        public Comparable[] getAllInOrder() {
            Comparable[] list = new Comparable[nodeCount];
            inOrderVisit(root,list,0);
            return list;
        private int inOrderVisit(TreeNode pointer, Comparable[] list, int count) {
            if (pointer != null) {
                count = inOrderVisit(pointer.left, list, count);
                list[count++] = pointer.data;
                count = inOrderVisit(pointer.right, list, count);
            return count;
        public String toString() {
            StringBuffer result = new StringBuffer(100);
            inOrderString(root, result);
            return result.toString();
        private void inOrderString(TreeNode pointer, StringBuffer result) {
            if (pointer != null) {
                inOrderString(pointer.left, result);
                result.append(pointer.data.toString() + "\n");
                inOrderString(pointer.right, result);
    }Thanks for everyones help. Keep in mind i'm very new to java.

  • Problem with Binary Search.

    Hi Gurus.
    I am using binary search to read data from internal table with approx more than 3lacs records. Also my table is sorted by BUKRS BELNR. But the problem is that i am getting records from lower half of table only and first half of table is ignoring, so i am not able to get all records. If i use nornal search, i am geting 7856 records and if i use binary search, i am geting only 1786 records....Can anyone help me why this is happening????

    Hi PV
    Actually my table contain line items. I am reading header data from bkpf for a single day. and for that document nos i am fetching line items. But if i use join or for all entries, i will get time exceed errror. so i get Period of that single day and taking data for that period from BSIS and then reading BKPF.. and only taking that line items for which document no in BKPF...
    my code is like
    SELECT-OPTIONS: cpudt FOR sy-datum DEFAULT '20030102'.
    SELECT bukrs belnr gjahr monat FROM bkpf
    INTO CORRESPONDING FIELDS OF TABLE ibkpf
    WHERE ( cpudt IN cpudt OR aedat IN cpudt ).
    ibkpf1[] = ibkpf[].
    SORT ibkpf1 BY monat.
    DELETE ADJACENT DUPLICATES FROM ibkpf1 COMPARING monat.
    IF ibkpf1[] IS NOT INITIAL.
      SELECT * FROM bsis INTO TABLE ibsis
          FOR ALL ENTRIES IN ibkpf1 WHERE gjahr = ibkpf1-gjahr
                                     AND monat = ibkpf1-monat.
      SORT ibsis BY bukrs belnr.
      LOOP AT ibsis.
        READ TABLE ibkpf WITH KEY bukrs = ibsis-bukrs
                                  belnr = ibsis-belnr
                                  BINARY SEARCH.
        IF sy-subrc NE 0.
          DELETE ibsis.
        ENDIF.
      ENDLOOP.
    ENDIF.

  • Binary search in text files

    Hi all,
    I'm thinking about how to implement a binary sort to get,given a key, a value from a text file with a list of words in order. I saw randomaccessfile for j2se and I know that this work it's usually done by seek functions but how to do the seek work without the File class , with only the InputStream and Reader? I'm talking about the j2me midp 2 cldc 1.1 api, is there some methods or class to use for this thing? How could be implemented a binary search in a text file resident in the /res dir or the JAR or which could be the problems that cannot make possible this staff? If there was something like seek one way could be that one of decide a common length of words to read so going to the half of the text file it's possible with simply multiplication, and the do the binary search things.But for now I haven't found any resources or help.
    I hope you can help me to understand, thank you

    Hallo all,
    it is NOT the problem to locate the text I need to find in the fmb, or fmx.
    The problem is that since I want to change not only the text but also some more code around I want to do this in Form Builder - Object Navigator. And I'm not able to discover in which trigger or procedure the text appears.
    I do not want to edit fmx, or fmb in a text editor because I suupose theer are some checksums hidden for the format.
    -duro
    BTW in FMT there is no code seen (only some binary) for v6i as it was in v4.5.

Maybe you are looking for

  • Problem with: Upload file thru Web access.

    We have configure iFS 1.1 on AIX 4.3. Everything is running fine like ifsstart, ifsmgr. Its showing me all protocols and agents running. I am able to access iFS through web access program and its accepting login and password. After login in to iFS se

  • Trying to hard wire 2nd mac using another airport extreme

    Ok. i currently have an airport express(in my kitchen)that i use with my ibook (wirelessly) and everything works great. The problem is that i have another mac that is upstairs that i wish to have hooked up as well via LAN. (i have to do it this way b

  • Button Toggle ADF Javascript(Works in Firefox but not in IE. why ?)

    I have written a code to toggle button in ADF as follows: <af:resource type="javascript"> function enableDisable(actionEvent){ alert("21"); document.getElementById('cb1').style.background='red'; document.getElementById('cb2').style.background='green'

  • Pdf as print and never/not interactive

    hi, is it possible to change the default pdf format from "interactive" to "print" - we would never use the interactive format and this i pretty annoying

  • Software Update crashes during check

    Yesterday I installed Security Update 2005-009 via Software Update to my 10.4.3 up-to-date system (I installed everythig software update suggested). Today daily software update check crashes: Link (dyld) error: Symbol not found: __ZN3KJS7UString7rele