Stefza Stefza - 9 days ago 5
Java Question

Sorting an object array using Insert and Selection sorts

I need to create a method to sort an Object Array. I've never done this, but I must revise this for my course. I'm totally lost when it comes to implementing a sorting method. I need to sort using a insertion sort and selection sort.

This is my code I have so far in. All I must do is call the sort() when the user wishes to do so.

package citylisttest;

public class CityList {
private City[] city;
private Integer numberOfCities;

public CityList (Integer cityListSize){
this.city=new City[cityListSize];
this.numberOfCities=0;
}

public void addCity(String city){
this.city[this.numberOfCities]=new City(city);
this.numberOfCities++;
}

public String toString(){
String cityDetails=new String();
if (this.numberOfCities!=0){
cityDetails+=String.format("%-15s\n","CITY");
for(Integer i=0;i<this.numberOfCities;i++) {
cityDetails+=this.city[i]+"\n"; }
}
else
cityDetails+="City list is empty";
return cityDetails;
}

public void sort(){

}
}

Answer

First, I would suggest renaming the variable city to cities since it is an array, and it holds more than one city. In addition, also consider encapsulating your data by marking as private your instance variable and creating getters and setters respectively.

Let's say you want to sort them by number of cities in ascending order, then your sort method should have:

for (int i = 0; i < city.length - 1; i++) {
    for (int j = i + 1; j < city.length; j++) {
        if (city[i].getNumberOfCities() > city[j].getNumberOfCities()) {
            City temp_city = city[i];
            city[i] = city[j];
            city[j] = temp_city;
        }
    }
}

I hope this helps, but you can implement the Comparable interface or create a Comparator class following this tutorial.

EDIT: If you want to use compareto, to sort city names in ascending order:

for (int i = 0; i < city.length - 1; i++) {
    for (int j = i + 1; j < city.length; j++) {
        if (city[i].getName().compareTo(city[j].getName()) > 1) {
            City temp_city = city[i];
            city[i] = city[j];
            city[j] = temp_city;
        }
    }
}

Assumming x, and y are strings, x.compareTo(y) gives you:

a positive number if x > y

zero if x is equal to y

a negative number if x