0

So I was trying to sort words alphabetically using linear sort and delete the word if there is already a word like it. I used the following method:

import java.util.Arrays;

public class Sorting {

    public static void main(String[] args) {

        String[] array = new String[] { "pepperoni", "ham", "bacon",
                "pineapple", "ham", "sausage", "onion", "bacon" };

        System.out.println("Before sorting: " + Arrays.toString(array));

        for (int i = 0; i < array.length; i++) {
            int min = i;

            for (int j = i; j < array.length; j++) {

                if (array[min].compareTo(array[j]) > 0) {
                    min = j;
                }

                else if (array[min].equals(array[j]) == true) {
                    array[j] = "";
                }
            }

            String tmp = array[i];
            array[i] = array[min];
            array[min] = tmp;
        }
        System.out.println("After sorting: " + Arrays.toString(array));
    }
}

But everything is deleted. Without the else if statement it will be sorted out, but with it everything is deleted.

Before sorting: [pepperoni, ham, bacon, pineapple, ham, sausage, onion, bacon]
After sorting: [, , , , , , , ]

Can someone point out what's wrong with this code?

Daniel
  • 387
  • 1
  • 7
  • 17
newbie
  • 33
  • 1
  • 7
  • `if(array[min].equals(array[j]) == true)`? See http://stackoverflow.com/questions/404838/do-you-prefer-if-var-or-if-var-0/404846#404846 – paxdiablo Jul 21 '15 at 07:20

1 Answers1

4

I think the two for should be:

for(i = 0; i < array.length - 1; i++)

and

for(j = i + 1; j < array.length; j++)

So you are sure that i and j are always different. In your implementation in fact, you always compare the element with the element itself, and you (wrongly) assume that it's a duplicate.

Moreover you can use:

if(array[min] < array[j])

and

else if(array[min].equals(array[j]))
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115