Priority Queue using ArrayList

PHOTO EMBED

Wed Jun 05 2024 18:52:27 GMT+0000 (Coordinated Universal Time)

Saved by @chatgpt #java

//PriorityQueue using ArrayList

import java.util.*;

public class PriorityQueueDemo<K extends Comparable<K>, V>{
    static class Entry<K extends Comparable<K>, V>{
        private K key;
        private V value;
        
        public Entry(K key, V value){
            this.key = key;
            this.value = value;
        }
        
        public K getKey(){
            return this.key;
        }
        
        public V getValue(){
            return this.value;
        }
        
        
    }
    
    private ArrayList<Entry<K,V>> list = new ArrayList<>();
    
    public void insert(K key, V value){
        Entry<K,V> entry = new Entry<>(key,value);
        int insertIndex = 0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getKey().compareTo(key)>0)
                break;
            insertIndex++;
        }
        list.add(insertIndex, entry);
    }
    
    public K getMinKey(){
        return list.get(0).getKey();
    }
    
    public V getMinValue(){
        return list.get(0).getValue();
    }
    
     public static void main(String[] args){
        PriorityQueueDemo<Integer, String> p = new PriorityQueueDemo<>();
        p.insert(5,"hello");
        p.insert(2,"java");
        p.insert(1, "programming");
        p.insert(3, "welcome");
        
        System.out.println("Minimum Key: "+p.getMinKey());
        System.out.println("Minimum Value: "+p.getMinValue());
    }
}
content_copyCOPY