Mina
Mina

Reputation: 45

Trouble with Properly Sorting Array in Alphabetical Order

I'm having a problem with a part of my code. It has to sort by name in alphabetical order but seems to do it in a descending way. Can someone guide me on what changes I should make in order for the output to display the data properly? Thank you.

Here is my sorting code:

//Method sortName
            public static void sortName() throws IOException {

            //Selection Sort
            for (x = 0; x < 8; x++) {
                smallest = x;

            for(i = x + 1; i < 8; i++) {

                //Compare current smallest
                //to the current position in the array
                if(name[i].compareTo(name[smallest])> 0) {
                    smallest = i;
                }

            }
                //Swap smallest element with position in array      
                temp = name [x];
                name [x] = name [smallest];
                name [smallest] = temp;

                temp = crime [x];
                crime [x] = crime [smallest];
                crime [smallest] = temp;

                temp = year [x];
                year [x] = year [smallest];
                year [smallest] = temp;

            }
            //Display each category of records; names, crime, year
            System.out.print("Name" + " ----" + "Crime" + "----" + "Year\n");

            //output
            for (x = 0; x < 8; x++) {

                //Display each sorted criminal name with the crime and year. 
                System.out.println(name[x] + " --- " + crime[x] + " --- " + year[x]);

Here is my output:

Name ----Crime----Year
Slippery Sal --- Arson --- 1997
Natasha Ora --- Theft --- 2007
Kate Olaf --- Assault --- 1984
Eddie Striker --- Arson --- 1978
Bugs Malone --- Theft --- 1981
Bob Allen --- Assault --- 1957
Anne Wilson --- Arson --- 2013

Upvotes: 0

Views: 43

Answers (1)

Steffen Harbich
Steffen Harbich

Reputation: 2749

Have a look at the compareTo javadoc. It states:

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

In your line

if(name[i].compareTo(name[smallest])> 0) {

the mentioned "this object" is name[i] and the "specified object" is name[smallest]. And you want to exchange when name[i] is less then name[smallest]. So either you swap name[i] and name[smallest], or you change the comparison to < 0.

Also I always recommend to execute the code with the debugger step-by-step when testing it the first time, and especially when there is unexpected behavior.

Upvotes: 1

Related Questions