Priority Queue program in java

 //Priority Queue

interface QueueADT<E extends Comparable<E>>

{

void enqueue(E element);

E dequeue();

E peek();

int size();

boolean isEmpty();

}

class MyQueue<E extends Comparable<E>> implements QueueADT<E>

{

private E[] arr;

private int front;

private int rear;

private int size;

public MyQueue(E[] arr)

{

this.arr=arr;

front=-1;

rear=-1;

size=0;

}

public void enqueue(E element)

{

if(rear==arr.length-1)

{

System.out.println("Queue Overflow");

}

else

{

rear++;

arr[rear]=element;

size++;

//rearrange method will automatically arrage all the elements at its appropriate place

rearrange(arr);

}

}

public void rearrange(E[] arr)

{

for(int i=rear; i>front+1; i--)

{

if(arr[i].compareTo(arr[i-1])<0)

{

//swap

E temp=arr[i];

arr[i]=arr[i-1];

arr[i-1]=temp;

}

else

{

break;

}

}

}

public E dequeue()

{

return null;

}

public E peek()

{

return null;

}

public int size()

{

return 0;

}

public boolean isEmpty()

{

return size==0;

}

public void traverse()

{

System.out.println("Elements of Queue :");

for(int i=front+1; i<=rear; i++)

{

System.out.print(arr[i]+", ");

}

System.out.println();

}

}

class Student implements Comparable<Student>

{

private int rollNo;

private String name;

public int compareTo(Student o)

{

System.out.println("Roll no:"+rollNo);

System.out.println("Student Roll no"+o.rollNo);

System.out.println("Result:"+(rollNo-o.rollNo));

return rollNo-o.rollNo;

}

public Student(int rollNo,String name)

{

this.rollNo=rollNo;

this.name=name;

}

public int getRollNo()

{

return rollNo;

}

public void setRollNo(int rollNo)

{

this.rollNo=rollNo;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name=name;

}

public String toString()

{

return "["+name+", "+rollNo+"]";

}

}


class PriorityQueue

{

public static void main(String aths[])

{

Integer[] arr=new Integer[10];

MyQueue<Integer> queue=new MyQueue<>(arr);

queue.enqueue(50);

queue.enqueue(25);

queue.enqueue(65);

queue.traverse();

//student object

Student s=new Student(3,"aman");

Student s1=new Student(2,"ramesh");

Student s2=new Student(1,"aankit");

Student brr[]=new Student[10];

MyQueue<Student> studentMyQueue=new MyQueue<>(brr);

studentMyQueue.enqueue(s);

studentMyQueue.enqueue(s1);

studentMyQueue.enqueue(s2);

studentMyQueue.traverse();

}

}



Post a Comment

0 Comments