How do I sort string in the Insertion Sort method?

Asked

Viewed 1,179 times

1

I’m with the following method, but in the WHILE line it’s error. netbeans says

"bad operand types for Binary Operator "&&", first type: Boolean, Second type: int".

public boolean insertionSort(String a []) {
        if (a == null) return false;   
        int i,j;  String x;
        for ( i=0; i < a.length; i++ ) {       
            x = a[i]; j = i;
            while (j>0  && x.compareTo(a[j-1])) {
                a[j] = a[j-1];
                j--;
            }
            a[j] = x;
            visualizarEtapa(a,i);
        }
        return true;
}

1 answer

1

The method .compareTo returns an int (-1 for smaller, 0 for equal, and 1 for greater). This way, for you to compare you can use:

while (j>0  && 0 == x.compareTo(a[j-1]))

or

while (j>0  && x.equals(a[j-1]))

or using the Commons lang3 apache

while (j>0  && StringUtils.equals(x.compareTo(a[j-1]))

There are several ways to compare strings, in the first two examples you need to take great care to avoid Nullpointexception when x is null, always making validations before working with .compareTo or with the .equals

Edited code

public boolean insertionSort(String a []) {
        if (a == null) return false;   
        int i,j;  String x;
        for (j = 1; j < a.length; j++) {       
            x = a[j]; i = j - 1;

            while (i >= 0) {
                if (x.compareTo(a[i]) > 0) {
                    break;
                }
                a[i + 1] = a[i];
                i--;
            }
            a[i + 1] = x;
            System.out.println(Arrays.toString(a));
        }
        System.out.println(Arrays.toString(a));
        return true;
}
  • It worked! But the method was not ordering the values of the vector alphabetically yet. I changed the comparative "==" to ">". It looks like this: while (j>0 && 0 > x.compareTo(a[j-1]))

  • I got your code I made some changes, see if it works

Browser other questions tagged

You are not signed in. Login or sign up in order to post.