Skip to content

Priority Queue - Sort by HEIGHT (High to low) #86

Description

@SharedMocha

//VVIMP
//Comparator (this is used to display list is ascending or descending order)
//Comparable (this is to sort the array using a key like height,weight,age)

import java.util.*;
public class HelloWorld{

 public static void main(String []args){
PQS pqs = new PQS();
PriorityQueue<Height> temp = new PriorityQueue<>(5,pqs); Height hs1 =new Height("Hemanth",10);
Height hs2 =new Height("Divya",70);
Height hs3 =new Height("Suman",50);
Height hs4 =new Height("Lila",400);
Height hs5 =new Height("Prompt",-50);
temp.add(hs1);
temp.add(hs2);
temp.add(hs3);
temp.add(hs4);
temp.add(hs5);
while(!temp.isEmpty()){
System.out.println(temp.poll());
} }

}

class Height implements Comparable{
String name;
Integer height;

public Height(String name,Integer height){
this.name = name;
this.height = height;
}
String getName(){
return name;
}
Integer getHeight(){
return height;
}
@Override
public String toString(){
return "The person is"+getName()+"-->"+getHeight();
}
@Override
public int compareTo(Height theOtherPersonsHeight){
int value = this.height.compareTo(theOtherPersonsHeight.height);
return value;
}

}
class PQS implements Comparator{
@OverRide
public int compare(Height one,Height two){
//System.out.println(one + " "+ two);
//return one.height-two.height;
return two.height-one.height;
}

 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions