I was writing a program for a quiz which requires me to sort some numbers and print the corresponding string.
For this, I created a class Song, and took an array of the objects of this class. I have to sort on the basis of variable qi. The problem is that according to the judge, my solution takes too much time and is not efficient enough. I earlier tried with an ArrayList of objects and switched to array thinking that could optimize it to an extent but it was of no help.
How can I optimize it further?
My Code:
class Song{
long fi;
long qi;
String si;
public Song(long fi,String si, long qi){
this.fi = fi;
this.si = si;
this.qi = qi;
}
}
public class Zipf {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
long fi;
long qi;
String si;
int noOfSongs = scan.nextInt();
int selection = scan.nextInt();
List<Song> list=new ArrayList<Song>(); // all songs
TreeSet<Song> set = new TreeSet<Song>(new treeComparator());
for(int i=0; i< noOfSongs;i++)
{
fi=(scan.nextLong());
si=(scan.next());
qi=(fi*(i+1));
list.add(new Song(fi,si,qi));//adding all songs to list
}
for(int i=0; i< selection;i++)
{
set.add(list.get(i));//adding no of songs to be selected into set
}
Song min = set.first();
for (int i = selection; i < list.size(); i++) {
Song song = list.get(i);
if (song.qi > min.qi) {
set.remove(min);
set.add(song);
min = set.first();
}
}
Iterator<Song> iterator = set.descendingIterator();
//Displaying the Tree set data
for(int i=0;i<selection;i++){
System.out.println(iterator.next().si);
}
}
}
class treeComparator implements Comparator<Song>{
@Override
public int compare(Song o1, Song o2) {
if (o1.qi <= o2.qi) return -1;
if (o1.qi > o2.qi) return 1;
return 0;
}
}
Longobjects and useLong.compare(song1.qi, song2.qi)instead. Maybe there is something else in the code you did not post?