How do I sort string in the Insertion sort method?

1

I'm using the following method, however 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;
}
    
asked by anonymous 05.03.2017 / 02:46

1 answer

1

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

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

or

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

or by using the commons lang3 from 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 be very careful to avoid NullPointException when x is null, always validating before working with .compareTo or .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;
}
    
05.03.2017 / 05:49