1

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(){

    }
}
2

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

I understand how to do this, its just using compareto which confuses me. I need to sort in Alphabetical order, but thanks for the tips.
@Stefza, I have edited my answer, and I have also added a brief explanation about compareTo
@Stefza, although I know you need selection or insertion sort, I have used bubble sort in order to allow you to figure out the correct answer. In case you need a guide you can see this github.com/bit0001/SortAndSearchAlgorithms which contains several sorting algorithms implemented in Python.
Sorry for the late reply. Thanks for the help! Ive looked at notes for the sorts and still cant get it into my head haha! Guess it will take time.
0

Documentation about this topic is really common to find in internet, but "let me google that for you".

I would suggest to understand what you want to do. Therefore I would suggest you to take a look at first, what is a sorting algorithm:

https://en.wikipedia.org/wiki/Sorting_algorithm

and then, particularly to the insertion sort algorithm:

https://en.wikipedia.org/wiki/Insertion_sort

or the selection sort:

https://en.wikipedia.org/wiki/Selection_sort

Someone can give you the answer here, but if you do not struggle with the problem, you will not learn about it and you will forget soon about it.

Hope it helps :)

Comments

0

This looks very much like a homework question, as the common practice is not to create your own sort algorithm.

You'll get further by attempting to design your own solution, even if it's naive, than copy/pasting whatever answer you find here.

If you really want to explore the various possible solutions (with java source code) you can follow this applet and tutorial:

https://thomas.baudel.name/Visualisation/VisuTri/

Comments

0

Here are the codes. But before going there I think you should watch these two videos:

insertionSort: https://www.youtube.com/watch?v=DFG-XuyPYUQ&t=142s

selectionsort: https://www.youtube.com/watch?v=f8hXR_Hvybo

public static void insertionSort(Object[] data) {
// i denotes where the partition is
for (int i = 1; i < data.length; i++) {
// the key is to the right of the partition
Object key = data[i];
int j = i - 1; // use j to scan left to insert key
while (j >= 0 && ((Comparable) key).compareTo(data[j]) < 0) {
// shift item right to make room
data[j + 1] = data[j];
j--;
}
// Found the position where key can be inserted
data[j + 1] = key;
}
}

public static void selectionSort(Object[] data) {
for (int i = 0; i < data.length - 1; i++) {
// Find the index of the minimum item, starting at `i'.
int minIndex = i;
for (int j = i + 1; j < data.length; j++) {
if (((Comparable) data[j]).compareTo(data[minIndex]) < 0)
minIndex = j;
// Exchange with the first item (at `i'), but only if different
if (i != minIndex) {
Object tmp = data[i];
data[i] = data[minIndex];
data[minIndex] = tmp;
}
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.