import java.text.*;
import java.util.Date;
public class SortingSongs {
static DateFormat df = new SimpleDateFormat("dd MMM yyyy");
static Object[][] songs = {
// track artist album date
{ "Blue Universe", "Craig Chaquico", "Once In A Blue Universe",
getDate("01 Jun 1997") },
{ "Hymn For Her", "Rick Braun", "Body And Soul",
getDate("25 Jan 1997") },
{ "Magic", "Ken Navarro", "Smooth Sensation",
getDate("14 Oct 1997") },
{ "After The Rain", "Boney James", "Sweet Thing",
getDate("12 Mar 1997") }
};
static int[] catSizes;
public static void main(String[] args) {
initCatSizes();
// Sort by category, viz, column in songs.
for(int j = 0; j < songs[0].length; j++) {
sort(j);
print();
System.out.println("-----------------");
}
}
private static void sort(int cat) {
int c = 0;
for(int j = 0; j < songs.length; j++) {
for(int k = j+1; k < songs[j].length; k++) {
if(cat < 3)
c = ((String)songs[j][cat]).compareTo((String)songs[k][cat]);
else
c = ((Date)songs[j][cat]).compareTo((Date)songs[k][cat]);
if(c > 0) {
Object[] temp = songs[j];
songs[j] = songs[k];
songs[k] = temp;
}
}
}
}
private static void print() {
for(int j = 0; j < songs.length; j++) {
for(int k = 0; k < songs[j].length; k++) {
String s = getString(j, k);
int spaces = catSizes[k] - s.length();
System.out.print(s + space(spaces));
if(k < songs[j].length-1)
System.out.print(" ");
}
System.out.println();
}
}
private static Date getDate(String s) {
Date date = null;
try {
date = df.parse(s);
} catch(ParseException e) {
System.out.println("Parse error for: " + s);
}
return date;
}
private static void initCatSizes() {
int numCats = songs[0].length;
catSizes = new int[numCats];
for(int col = 0; col < numCats; col++) {
int max = 0;
for(int row = 0; row < songs.length; row++) {
int length = getString(row, col).length();
if(length > max)
max = length;
}
catSizes[col] = max;
}
}
private static String getString(int row, int col) {
if(col == 3)
return df.format(songs[row][col]);
return (String)songs[row][col];
}
private static String space(int n) {
String s = "";
for(int j = 0; j < n; j++)
s += " ";
return s;
}
}