Provided below is my current code for sorting list of song objects using inserti
ID: 3791821 • Letter: P
Question
Provided below is my current code for sorting list of song objects using insertion sort. It doesn't seem to work however. Please help!!
public void sortSongsList() { //Sort songsList alphabetically String s = songsList.get(0).getName(); // s.compareTo() for (int i = 1; i < songsList.size(); i++) { for (int j = 1; j < songsList.size(); j++) { if (songsList.get(i).getName().compareTo(songsList.get(j).getName()) < 0) { Song t = songsList.get(j); Song s1 = songsList.get(j); Song s2 = songsList.get(j); s1 = songsList.get(j - 1); s2 = t; } } }Explanation / Answer
public void sortSongsList() {
int n=songsList.size();//get the length of list
//performing insertion sort
for (int j = 1; j < n; j++) {
String s=songsList.get(j).getName();
int i=j-1;
while((i>-1) && (s.compareTo(songsList.get(i).getName())>0) {
//songsList.replace(i+1,i); // for replace the songs in list (swapping songs)
Song t=songsList.get(i-1);
Song t1=songsList.get(i);
songsList.replace(t,t1);
i--;
}
Song t2=songsList.get(j);
Song t3=songsList.get(i+1);
songsList.replace(t3,t2);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.