Home > other >  Swapping two elements of a vector without creating new objects?
Swapping two elements of a vector without creating new objects?

Time:11-08

I am new to Java coming from C . I want to that v(i) should point to the object of v(j) and vice versa that is the references of both of them must interchange. Please give some beginner friendly solution. I can't make new objects or just replace the parameters because it will affect the working of algorithm.

import java.util.*;
class maxPriorityQueue{
    public Vector<vertex> v;
    public int size;
    static final int infinite=2147483647;
    maxPriorityQueue(int s){
        this.size=s;;
        v=new Vector<vertex>(size);
    }
    int parent(int i){
        return (i-1)/2;
    }
    int leftChild(int i){
        return 2*i 1;
    }
    int rightChild(int i){
        return 2*i 2;
    }
    void swap(int i,int j){
        vertex temp=v.elementAt(i);
        v.elementAt(i)=v.elementAt(j);
        v.elementAt(j)=temp;
    }
    void minHeapify(int index){
        int smallest;
        int left=leftChild(index);
        int right=rightChild(index);
        if(left<size && v.elementAt(index).key>v.elementAt(left).key){
            smallest=left;
        }
        else{
            smallest=index;
        }
        if(right<size && v.elementAt(smallest).key>v.elementAt(right).key){
            smallest=right;
        }
        if(smallest!=index){
            swap(index,smallest);
            minHeapify(smallest);
        }
    }
    void builMinHeap(){
        for(int i=0;i<size/2;i  ){
            minHeapify(i);
        }
    }

};
class vertex{
    final int infinite=2147483647;
    int value;
    int key;
    vertex pi;
}
class edge{
    int u;
    int v;
    int weight;
}
class Graph{
}
class primsAlgo{
    public static void main(String[] args) {
        // vertex x=new vertex();
    }
}

error:

primsAlgo.java:21: error: unexpected type
        v.elementAt(i)=v.elementAt(j);
                   ^
  required: variable
  found:    value
primsAlgo.java:22: error: unexpected type
        v.elementAt(j)=temp;
                   ^
  required: variable
  found:    value
2 errors

CodePudding user response:

You have to use .setElementAt():

void swap(int i,int j){
    vertex temp=v.elementAt(i);
    v.setElementAt(i, v.elementAt(j));
    v.setElementAt(j, temp);
}
  • Related