This is not a question just small challenge if you interest in improving provided solution and feedback for me.
I just went back to some assignment I did at university and one of these been design phone book for mobile device with use of Java Microedition (JME). At the time I had no time to play around with certain functionalities and this included contact sorting. Initial contact list display only contact name and first number associated with the contact, plus ID from Record Management Store (RMS) to for easier contact look up.
These contacts are kept in ContactListLabels
public class ContactListLabel {
private int contactID;
private String nameLabel;
private String numberLabel;
public ContactListLabel(){}
public ContactListLabel(int id, String name, String number){
setContactID(id);
setNameLabel(name);
setNumberLabel(number);
}
private void setContactID(int id){contactID = id;}
public int getContactID(){ return contactID;}
private void setNameLabel(String name){nameLabel = name;}
public String getNameLabel(){ return nameLabel;}
private void setNumberLabel(String number){ numberLabel = number;}
public String getNumberLabel(){ return numberLabel;}
}
Problem with JME is that only Vector, HashMap and array are available. I decided to use Vector as it is more flexible that array for which I need to know size and swapping array elements would can cause more trouble then I want.
So when user select View Contacts option, first I fetch contacts from RMS and store them in ContactListLabel objects and then add them to Vector. Once all contacts are read I pass this vector to sorting method as seen below.
public Vector sortContacts(Vector v){
Vector sorted = new Vector();
ContactListLabel cll = (ContactListLabel) v.elementAt(0);
ContactListLabel cll2 = (ContactListLabel) v.elementAt(1);
if(cll.getNameLabel().compareTo(cll2.getNameLabel()) <= 0){
sorted.addElement(cll);
sorted.addElement(cll2);
}
else{
sorted.addElement(cll2);
sorted.addElement(cll);
}
for(int i = 2; i < v.size(); i++){
for(int y = 0; y < sorted.size()-1; y++){
cll = (ContactListLabel)sorted.elementAt(y);
cll2 = (ContactListLabel)sorted.elementAt(y+1);
ContactListLabel toInsert = (ContactListLabel)v.elementAt(i);
if(cll.getNameLabel().toLowerCase().compareTo(toInsert.getNameLabel().toLowerCase())> 0){
sorted.insertElementAt(toInsert, y);
y = sorted.size();
}
else if(cll.getNameLabel().toLowerCase().compareTo(toInsert.getNameLabel().toLowerCase()) <= 0 &&
cll2.getNameLabel().toLowerCase().compareTo(toInsert.getNameLabel().toLowerCase())>0){
sorted.insertElementAt(toInsert, y+1);
y = sorted.size();
}
else if(cll2.getNameLabel().toLowerCase().compareTo(toInsert.getNameLabel().toLowerCase()) <= 0 && y+2 == sorted.size()){
sorted.addElement(toInsert);
y = sorted.size();
}
}
}
return sorted;
}
As you can see it is simple insertion. Have look at it and if you think there is some worth to change let me know. It doesn't matter if it is algorithm or my coding. I'm looking for all feedbacks!