sorting an array based on certain criteria
Hi there,
My project is to create a song list using an array and then be able to sort the songs based on different criteria. I've already set up a Song class which assigns values to the fields title, writer, singer, duration, genre, and year. Now I'm writing a SongList class which creates a song array that holds a max and also should be able to sort the songs in the list. It is supposed to be able to sort by writer, duration, genre, and year using either bubble sort or selection sort. What I have right now is selection sort, but I don't understand what I need to do for these and have mostly just been trying to write something that compiles even though I'm pretty sure it won't work. Any help would be much appreciated.
This is what I have so far for the SongList class:
Code:
public class SongList
{
private static final int MAX = 50;
private Song[] songList;
private int size;
/**
* Constructor for objects of class SongList
*/
public SongList()
{
songList = new Song[MAX];
size = 0;
}
/**
* Adds a song into the array.
*
* @param s size
* @return true or false
*/
public boolean addSong(Song s)
{
if(size <= MAX)
{
songList[size] = s;
++size;
return true;
}
else
{
return false;
}
}
/**
* Finds a song in the array by the title.
*/
public int findSong(String title)
{
int index = 0;
boolean found = false;
while(index < size && !found)
{
if(title.equals(title))
{
index++;
found = true;
}
}
return index;
}
/**
* Swaps two songs in the array.
*/
public void swapSong(int a, int b)
{
Song temp = songList[a];
songList[a] = songList[b];
songList[b] = temp;
}
/**
* Sorts the songs by the writer.
*/
public void sortByWriter()
{
for(int i = songList.length-1; i>0; i--)
{
int first = 0;
for(int j = 1; j<=i; j++)
{
if(songList[j]==(songList[first]))
{
first = j;
}
}
Song temp = songList[first];
songList[first] = songList[i];
songList[i] = temp;
}
}
Re: sorting an array based on certain criteria
Quote:
sort the songs based on different criteria.
Look at the Arrays class's sort() method. You can create a Comparator object for any criteria that you want.
Using your comparator object in the sort() method will sort the array in your desired order.
Re: sorting an array based on certain criteria
Quote:
It is supposed to be able to sort ... using either bubble sort or selection sort.
If this is a homework which requires that you don't use the infinitely preferable Arrays.sort(), you should say.