Deleting elements from a binary heap

I have to create a binary heap class and perform various operations. Every operation works except deleteMin, which gives an "ArrayIndexOutOfBoundsException: -1" exception in every case I've tried. Supposedly it's coming from line 85, which I put a line comment next to in the code below.
     * Deletes the smallest element (the root) from the heap and returns that value.
     * The heap is then reordered so that it is still a valid heap.
     * @return the root of the heap, a T type value
    public T deleteMin(){
        if(size == 0)
            throw new MyException();
        T returnValue = arr[0];
        T item = arr[size-1];
        size--;
        int hole = 0;
        int newHole = newHole(hole, item);
        while(newHole < arr.length - 1){
            arr[hole] = arr[newHole];  // ERROR IS HERE?
            hole = newHole;
            newHole = newHole(hole, item);
        arr[hole] = item;
        return returnValue;
     * Gives the index of where the next hole in the heap will be.
     * @param hole the index of the current hole
     * @param item the last element in the heap
     * @return the index of the next hole to be checked
    private int newHole(int hole, T item){
        int newHole = -1;
        if(arr[2*hole + 1] != null || arr[2*hole + 2] != null){
            if(arr[2*hole + 2] == null){
                if((arr[2*hole + 1]).compareTo(item) < 0){
                    newHole = 2*hole + 1;
            else {
                int smallerItem;
                // may need >= param
                if((arr[2*hole + 1]).compareTo(arr[2*hole + 2]) > 0)
                    smallerItem = 2*hole + 2;
                else
                    smallerItem = 2*hole + 1;
                if((arr[smallerItem]).compareTo(item) < 0)
                    newHole = smallerItem;
        return newHole;
    }I know I set newHole = -1 in the private method, which may be the problem, but the pseudo code my teacher gave me says to do just that. She gave us the pseudo code using a heap of int, the code is designed for a generic, comparable class. The test class uses a heap<String>. I just can't see why the problem is arising. Can anyone see where I've gone wrong?
Edited by: sublimeph03nix on Apr 23, 2009 1:57 PM
Edited by: sublimeph03nix on Apr 23, 2009 2:03 PM

arr[hole] = arr[newHole]; // ERROR IS HERE?I'd say that I bet newHole == -1, so you're trying to access element -1 in the array, which of course is out of bounds.
You have heard about debuggers, haven't you?

Similar Messages

  • How to delete elements from a cluster?

    Hello. I would like to know how to delete elements from a cluster. I got stuck with this problem. There is its own order of each element in a cluster. I tried to initiate an array but it seems like too complicated. In the attached file, I want to obtain only the data from "flow" not "pressure". I try to use array programming but it doesn't work. Would be nice if you help me to fix the file. Thanks
    Solved!
    Go to Solution.
    Attachments:
    test 1.vi ‏16 KB

    Bombbooo wrote:
    What about if I want to store data into the pressure array too? Do I have to create another loop or it can be done in the same loop as the flow loop?
    Try this, for example. Modify as needed.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    test1MOD2.vi ‏9 KB
    SelectFlowOrPressure.png ‏7 KB

  • Add/Delete elements from viewcontaineruielement in web dynpro abap

    Dear all,
    Please let me know how to Add/Delete elements from viewcontaineruielement in web dynpro abap? I have copied a viewcontaineruielement from another program and now i dont want few elements from that viewcontaineruielement in my view. Please guide

    Hi Ajinkya,
    I have copied a viewcontaineruielement from another program and now i dont want few elements from that viewcontaineruielement in my view. Please guide
    Have you saved that VC element as template and using that template in another component?.If so,on resuing that VC element template it populates all the screen elements which you've save as template.
    Now, select that VC element which you've re-used,based on you're requirement add/remove UI elements as Kiran suggested.
    Hope it will resolve your issue.
    Thanks
    KH

  • Deleting element from binary search tree

    please could u tell me what is the wrong with this deleting function ..
         private  BTNode deleteElement(int a,BTNode curNode)
              BTNode s,q,p;
              if (curNode==null)
              return curNode;
              HasId curObject =(HasId)curNode.getInfo();
              if (a>curObject.getId())
               curNode=deleteElement(a,curNode.getRight());     
               return curNode;
              else if (a<curObject.getId())
                   curNode=deleteElement(a,curNode.getLeft());
                   return curNode;
              else
                   q=curNode;
                   s=curNode;
                   if (q.getRight()==null)
                   curNode=q.getLeft();
                   else if (q.getLeft()==null)
                   curNode=q.getRight();
                        else{
                   p=q.getRight();
                   while (p.getLeft()!=null)
                        s=p;
                        p=p.getLeft();
                   curNode=p;
                   curNode.setLeft(q.getLeft());
                   s.setLeft(p.getRight());
                   if (q.getLeft()==p)
                   curNode.setRight(q.getRight());
                   else
                   curNode.setRight(p.getRight());
                   return curNode;
         public void delete(int a)
              deleteElement(a,root);
         }

    Very confusing code for the case a == curObjec.getId()
    Try giving meaningful names to the nodes instead of p, q, r, and adding some comments. It also looks like you could do with less node references than curnode, p, q and r, you are throwing them around a lot which is quite confusing.
    I find he following a bit weird:
    while (p.getLeft()!=null)
                        s=p;
                        p=p.getLeft();
                   }I don't know why you are making a path that always goes to the left child node while you already found a node to be deleted. Also I would think that a binary tree should be symmetric, so why only go to the left?
    If you got the delete algorithm from a book or website try to look exactly where your code goes wrong. Otherwise try running your code in your mind on a simple example tree and see if you find an error.

  • Deleting elements from Arrays.

    Hello,
    I have to be able in this latest exercise to delete an element from an Array. I was wondering if you could give me code examples on how to do this. I am pretty sure that you have to read through the array and return "null" when you hit the element that you want to delete in the array.
    Thank you.

    Look through the forum. There are at least two other threads open with people asking the same question.

  • Delete elements from XML file using DOM and java

    Hi
    I want now is to remove element from my XML file
    for example
    i have following xml
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
              <firstLineText />
              <firstLineText>|line11</firstLineText>
              <firstLineText>|line12</firstLineText>
    </firstLineTexts>
    </printing>how do i remove all elements fireLineText
    my final output should be
    <?xml version="1.0" encoding="UTF-8"?>
    <printing>
    <firstLineTexts>
    </firstLineTexts>
    </printing>How do i do it using DOM,
    I can create instance of DOM and write it using TransformerFactory
    Ashish

    Hi
    I am trying the following code,
    but it is not working
                    NodeList nScene = doc.getElementsByTagName("firstLineTexts");
              NodeList nScene1 = nScene.item(0).getChildNodes();
              for (int i = 0; i < nScene1.getLength(); i++)
                   Node n = nScene1.item(i);
                        nScene.item(0).removeChild(n);
              }

  • Delete element from a collection (JDev 10.1.2)

    Hello
    I have a bean which has a collection "testCollection" and accessors for it. This has been populated with some elements (similar to the LDAPDataControls example). I have created the data control for it and dragged the collection onto a JSP as a read only form. This displays the current element of the collection depending on the iterator position.
    I then have a forward on the page using a button to a Data Action called RemoveAction. I have overwritten invokeCustomMethod and I'm trying to remove the element in the collection at the current iteraotr position.
    I can access the iterator using actionContext.getBindingContainer().findIterator("testCollectionIterator");
    From this I can get the current row but both row.remove() and row.removeFromCollection throw UnsupportedMethod exceptions.
    I can access the collection using actionBinding.getBindingContainer().getDataControl().getDataProvider(), but I have no way of removing the object from the collection without having a reference to the object itself.
    Please can someone explain how to remove elements from the collection?
    Also can someone explain in the LDAPDataControls example why its also necessary to have a class called LDAPDataControl (type of DCGenericDataControl) and a LDAPDataControlFactory (type of DataControlFactoryImpl)?
    Just having the classes LDAPSearch, the bean class LDAPEntry, and a class to hold the collection LDAPCollection works fine. Create the data control for LDAPCollection and drag the collection onto the JSP.
    Thanks.

    I'm still not sure about this. Can anyone help? Thanks.

  • Deleting a single element from a binary file

    I am working on a server application that must keep track of the messages that have been sent but not responded to.  After I send a message, I append it to an array cycling through an uninitialized shift register and I write it to the end of a binary file.  When I receive a response to a message, which was probably but not necessarily the first message sent, I delete that message from the array and the file.  This allows me to look up entries quickly but also to maintain a permanent record of what messages have been sent and not responded to.
    Basically, I need an intelligent way to make a file, or any other permanent storage medium, act effectively like a queue.  The problem with the current implementation is that when I delete one variable-sized entry from the file, I need to move all subsequent entries, which are usually all of the other entries in the file, forward in memory to take its place.  Is there a way to get around recopying the majority of the file or to implement this entire thing more intelligently?

    You can organize your datafile as a list. For example In this list any record consists of a fixed size data field and referencies (file position f.e.) to the next record and  to the previous record. You can then rewrite the record-have-to-be-deleted with new one, or you can "delete" this record modifiyng the referencies of the "previous" and the "next" records. When you will add a new record you can write one at this "free" place.
    The other way is to manage two files. The first one contains your data record by record. The second one contains the numbers of the records and the corresponding datafile positions or record counter. This second file can be very small and easy-to-manage. It can represent the only record's queue position in the datafile. You can rewrite your records, mark them as deleted without moving large portions of data.
    You can setup the datafile capacity in "number of records" term.
    Additionally it is possible to use the records with variable length but it will be much more dificult. 
    Best regards, Evgeny. 

  • How to completely delete Photoshop Elements from my computer??

    Hi
    I am trying to completely remove Photoshop Elements from my computer.   So far, I have failed in my attempts to do this.   The reason I'm doing this is b/c for some reason that I can't fathom, the folders in My Pictures -- the folders named by shot date -- contain random duplicates.When this happens, the file names folow the convention of DSC_0222 and DSC_0222-1. Exactly the same file size and metadata.  In some folders, every picture is duplicated. In other folders, only selected pitcures within the folder are duplicated.   I can't figure out how they got there -- e.g. it doesn't seem to bear any connection to the photos I've edited, which was one theory I had for a while.   Is Elements responsible? Or is this some sort of bug in the download process from the camera (I have a Nikon D40).  Anyway, I've given up on trying to sovle this problem and decided I would go back to the beginning and reload everything from my camera.   So, my real question here is about how to completely uninstall Elements.
    Here's what I did:    I uninstalled Photoshop Elements through the Add/remove programs utility.  I got no errors during the uninstall process.   Then I completely deleted the My Pictures directory (don't worry -- I have it backed up in multiple places!!).   So, at this point there are *no* pictures on my computer at all.    I reinstall Elements, open it up and -- you guessed it!!! -- the catalog is still there with all the thumbnails of the pictures that i deleted from my hard disk.   Of course, each thumbnail is flagged as "Missing File".
    So, how do I uninstall/reinstall Elements and get it to forget all memory of the previous catalog?   Why is it "remembering" it in this way when the pictures aren't even on the computer anymore?  Isn't this a bug???
    I've been working on this issue for much longer than I care to remember-- if anyone can tell me how to get myself truly back to ground-zero so I can start over I would be deeply grateful.   After upgrading to Elements 9 (from 7) to try to solve this problem I am close to just abandoning Elements entirely.....
    WHile we're at it, if anyone has any idea where the duplicates pictures are coming from and how I prevent that from happening, I'm' all ears!!!!
    Thanks!

    Hi
    Thanks so much for the response.   So, Help/System Info says that the catalog is here:
    Catalog Location: C:\Documents and Settings\All Users\Application Data\Adobe\Elements Organizer\Catalogs\My Catalog\
    but no such file appaers to exist.  In fact, I can only get as far as All Users.   Then there is no directory under that called "Application Data".
    i'm still seeing the thumbnails when I got into Elements tho'....   :-(
    hjr

  • Deleting iWeb Elements from iDisk

    I'm sure this question has been posted before; but I couldn't find the answer. Excuse me if I'm being redundant.
    I know that when I delete a photo or other element from a page created with iWeb, it will no longer appear on the displayed page ... but will the file be deleted from my iDisk as well? I guess I'm being overly organized perhaps; but I would just like my iDisk to only contain what is actually needed for the website I create. (Also, unneeded files could result in a potential space problem eventually.
    I appreciate an answer from anyone who can shed light on my question. Thanks.
    iBook G4   Mac OS X (10.4.5)  

    There are some redundant files like duplicate copies of images and the like that iWeb publishes to your iDisk, but I think this is inherent in the design and html code generation of iWeb and I would not suggest delete files from your iDisk manually that appear to be duplicates to you. In any case, if ever any images are not necessary anymore (like if you delete a page from within iWeb), then iWeb will delete those images automatically from you iDisk.
    But every once in a while iWeb messes things up with the files on your iDisk and either keeps extra old files around or doesn't put up new ones for some reason. This causes strange effects like messed up rollovers, phantom images, etc. In this case, a "Publish All to .Mac" usually fixes things....it's like spring cleaning.

  • How do I delete photos in elements with out deleting them from my folders ?

    I am new to adobe. How do I delete images from elements 12 with out deleting them from my folders. ?

    When you select files to delete from catalog you get a dialog asking if you want to delete ALSO from disk : you don't. Simply don't check the check box.

  • Deleting pictures from elements

    I have been deleting pictures in elements to make more room on my hard drive and just noticed a box on the screen about deleting also from the hard drive.  Can anyone help me try and figure out how to sort out on my hard drive what pictures I have deleted from elements. Somethng easy and not too time consuming would be nice.  I am assuming that all this work I have been doing to delete pictures has not at all freed up anything on my hard drive.  ugh!
    I have looked at my "pictures folder" and nothing seems to be in folders or have any organization.  Since moving my elements to a new computer I have had to reconnect all my pictures.  Can I organize the pictures in folder and then if I ask elements or reconnect them will it be able to?

    It's really not a good idea to let elements delete the photos in any case. Your camera has its own directory structure that the computer doesn't fully understand. It's preferable to just reformat your card in the camera or delete the photos directly in the camera, rather than letting a computer do it for you.

  • Remove Deletion Flag from WBS Element

    Hi,
    Can anyone please tell me how cancel deletion flag from a WBS Element ? I set Deletion Flag on WBS Element by fault.
    BR//
    Rofique
    Edited by: akash2010 on Feb 18, 2011 6:57 AM
    Edited by: Virendra Pal on Feb 18, 2011 2:59 PM
    Basic Question

    The same way as you set it.
    Select the WBS Edit>Status>DeletionFlag-->Undo

  • Physical deletion of WBS elements from PRPS table

    Hi Experts,
    In CJ20N transaction:
    When I delete a project with project profile (ZABC), the following actions are performed:
    - The project entry are physically deleted from 'PROJ' table.
    - The WBS entries are physically deleted from 'PRPS' table.
    When I delete another with with project profile (ZXYZ), the following actions are perfomed:
    - The project entry are physically deleted from 'PROJ' table.
    - The WBS entries are NOT physically deleted from 'PRPS' table.
    What is the reason for not deleting entries physically from PRPS table?
    Thank you for your valuable answers.

    Hi Experts,
    In CJ20N transaction:
    When I delete a project with project profile (ZABC):
      - The project record is completely deleted from 'PROJ' table.
      - The WBS records are completely deleted from 'PRPS' table.
    When I delete another project with different project profile (ZXYZ):
      - The project record is completely deleted from 'PROJ' table.
      - The WBS records are NOT deleted from 'PRPS' table.
    What is the reason for not deleting records from PRPS table for another project (Project profile: ZXYZ)?
    Thanks in advance for your valuable answers.

  • How can i get all elements from a arraylist

    Hello everyone
    I have an arraylist with 40 elemets inside it.
    I want to be able to get the first 10 elements of the arraylist and put them into a sql statement (I can do this ok) but the problem is when i want to get the next 10 elements (from 10 to 20) they will not execute to the database. is this possible with just one prepared statement?
    thanks
    piper

    Hello Ken this is my code so far, And i keep getting the error
    binary data would be truncated.
    And if i change the values in the for loop i get an exception null.
    I do not know what is wrong with this so could you be so kind as to. help me thaks
    piper
    try {
          String data = "jdbc:odbc:myProject";
                 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
             Connection conn = DriverManager.getConnection(data,"","");
          int rows=0;
         PreparedStatement ps = conn.prepareStatement(
         "INSERT INTO Ben (Phone,addr1,addr2,PostCode) VALUES (?,?,?,?)");
              Iterator io = arr3.iterator();
                   while (io.hasNext())
                        for (int pos = 1; pos <=4; pos++)
                             String sf = (String)io.next();
                             ps.setString(pos,sf);
                        rows += ps.executeUpdate();
                        System.out.println("inserted" + rows + " rows");
         ps.close();
         return;
            }catch (Exception e1) {
                     System.err.println("Got an exception! ");
                     System.err.println(e1.getMessage());

Maybe you are looking for

  • Can't connect to SMTP Server

    Since upgrading to OS X Yosemite 10.10.3 I am no longer able to send email via my SMTP server. The SMTP server is the AWS SES service http://aws.amazon.com/ses/ and the smtp server name is email-smtp.eu-west-1.amazonaws.com. Apple Mail refuses to con

  • Adapter type for inbound xml message XI3.0 SP10

    Hi, We are using XI3.0 SP10 and are about to set up a scenario where we will receive an xml to process. Up until now we have only received simple flatfiles  to process. My question is, can I use adapter type "File" to process this inbound xml file? A

  • Posting here as there seems to be little activity in Shockwave forums

    Ok stupid question, but Do I have Shockwave player? I don't ever recall installing it nor do I want it but some odd things make me wonder if I have it If I do, then I haven't updated it and that concerns me. When I look in these location, I do not fi

  • Management IP unreachable

    Hello everyone!! I am facing this problem on different switches on my network on different days, the thing is that the switch is working fine and none of the users is facing in connection problem ,but I can not reach my switch (ping and telnet)from a

  • Cant get iCloud emails on my iOS devices

    Hi, This is been going on for a while. I was hoping the issue would resolves itself with upgrades but it never did. I had .mac, .me, and .iCloud e-mail accounts that always worked fine on my Mac's. On my iOS devices I had an .mac account. No problem