Code example for Vector

Methods: elementAt, setElementAt, size

0
    { 
        int left = lChild(cur);
        int right = rChild(cur);
        int smallest;
 
        if ((left < heap.size()) && 
        		(comp.compare(heap.elementAt(left), heap.elementAt(cur)) < 0)) {
			smallest = left;
		} else { 
			smallest = cur;
		} 
 
        if ((right < heap.size()) && 
        		(comp.compare(heap.elementAt(right), heap.elementAt(smallest)) < 0)) {
			smallest = right;
		} 
 
        if (cur != smallest)
        { 
            swap(cur, smallest);
            percolateDown(smallest);
        } 
    } 
 
    /** 
     * Moves the element <code>o</code> at position <code>cur</code>  
     * as high as it can go in the heap.  Returns the new position of the  
     * element in the heap. 
     */ 
    private int percolateUp(int cur, T o)
    { 
        int i = cur;
         
        while ((i > TOP) && (comp.compare(heap.elementAt(parent(i)), o) > 0))
        { 
            T parentElt = heap.elementAt(parent(i));
            heap.setElementAt(parentElt, i);
            object_indices.put(parentElt, new Integer(i));  // reset index to i (new location)
            i = parent(i);
        } 
         
        // place object in heap at appropriate place 
        object_indices.put(o, new Integer(i));
        heap.setElementAt(o, i);
 
        return i;
    } 
     
    /** 
     * Returns the index of the left child of the element at  
     * index <code>i</code> of the heap. 
     * @param i 
     * @return the index of the left child of the element at  
     * index <code>i</code> of the heap 
     */ 
    private int lChild(int i)
    { 
    	return (i<<1) + 1;
    } 
     
    /** 
     * Returns the index of the right child of the element at  
     * index <code>i</code> of the heap. 
     * @param i 
     * @return the index of the right child of the element at  
     * index <code>i</code> of the heap 
     */ 
    private int rChild(int i)
    { 
    	return (i<<1) + 2;
    } 
     
    /** 
     * Returns the index of the parent of the element at  
     * index <code>i</code> of the heap. 
     * @param i 
     * @return the index of the parent of the element at index i of the heap 
     */ 
    private int parent(int i)
    { 
    	return (i-1)>>1;
    } 
     
    /** 
     * Swaps the positions of the elements at indices <code>i</code> 
     * and <code>j</code> of the heap. 
     * @param i 
     * @param j 
     */ 
    private void swap(int i, int j)
    { 
        T iElt = heap.elementAt(i);
        T jElt = heap.elementAt(j);
 
        heap.setElementAt(jElt, i);
        object_indices.put(jElt, new Integer(i));
 
        heap.setElementAt(iElt, j);
        object_indices.put(iElt, new Integer(j));
    } 
     
    /** 
     * Comparator used if none is specified in the constructor.