I have a List of row objects. Each row has an id, name, and population.
Example:
Row x = new Row(305, Miami, 2.2);
I want to list the rows alphabetically by name using bubble sort. I know I need 2 loops for the bubble sort. This is what I get
protected void nameBubbleSort(List<AbstractRow> a) {
a=getcList();
int size = a.size();
int end = size-1; // size-1, so you don't get an IndexOutOfBoundsException
boolean sorted = false;
for(int i = 0; i < size-1 && !sorted; i++)
{
sorted = true; // if you never execute a swap, the list is already sorted
for (int j=0; j<end; j++) {
AbstractRow t1 = (AbstractRow) a.get(j);
AbstractRow t2 = (AbstractRow) a.get(j+1); // j+1, so you don't change the value of i
if(t1.getName().compareTo(t2.getName()) > 0)
{
sorted = false;
a.remove(j);
a.add(j+1, t1); // j+1, so you don't change the value of i
}
}
end--;
}
for(int i = 0; i<size; i++)
{
AbstractRow tmp = (AbstractRow) getcList().get(i);
System.out.println(tmp.toString()); }
}
protected void bubbleSortName(List<AbstractRow> list) {
list = getcList();
int n = list.size();
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (list.get(j - 1).getName() compareTo list.get(j).getName()) {
//swap elements
temp = aList.get(j - 1);
aList.set(j-1, aList.get(j));
aList.set(j, temp);
}
}
}
}
I then want to go back and sort using the id number.
Help please
protected void nameBubbleSort(List<AbstractRow> a) {
a=getcList();
int size = a.size();
int end = size-1; // size-1, so you don't get an IndexOutOfBoundsException
boolean sorted = false;
for(int i = 0; i < size-1 && !sorted; i++)
{
sorted = true; // if you never execute a swap, the list is already sorted
for (int j=0; j<end; j++) {
AbstractRow t1 = (AbstractRow) a.get(j);
AbstractRow t2 = (AbstractRow) a.get(j+1); // j+1, so you don't change the value of i
if(t1.getName().compareTo(t2.getName()) > 0)
{
sorted = false;
a.remove(j);
a.add(j+1, t1); // j+1, so you don't change the value of i
}
}
end--;
}
for(int i = 0; i<size; i++)
{
AbstractRow tmp = (AbstractRow) getcList().get(i);
System.out.println(tmp.toString()); }
}
protected void bubbleSortName(List<AbstractRow> list) {
list = getcList();
int n = list.size();
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (list.get(j - 1).getName() compareTo list.get(j).getName()) {
//swap elements
temp = list.get(j - 1);
list.set(j-1, list.get(j));
list.set(j, temp);
}
}
}
}
I know how to loop through the array list and get the length of each name, I'm just having a hard time pointing to the right object in the arrayList. I know thats what I have getName() and getID set up.