Search code examples
javasortingalphabeticalselection-sort

Sort an array alphabetically


I need to sort book objects by their titles in a simple way. However, the selection sort algorithm I wrote isn't working properly and just moves the books around, but with no apparent order. What am I doing wrong?

int j;
int b;

for (int i = 0; i < 20 - 1; i++) {
    int minIndex = i;

    for (j = i + 1; j < 20; j++) {
        b = (bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
        if (b < 0) {
            minIndex=j;
        }
    }

    Book temp = bookA[i];
    bookA[i] = bookA[j];
    bookA[j] = temp;
}

for (int z = 0; z < 20; z++)
    System.out.println(bookA[z].toString());

Solution

  • You're using j as an index in bookA[i] = bookA[j];. The problem is that you're overriding the value of j at every iteration, so when it finally gets to bookA[i] = bookA[j]; it will always be 20.

    What you want is to replace it with bookA[minIndex]. The resulting code would look like this:

    int j;
    int b;
    
    for(int i=0;i<20-1;i++){
        int minIndex=i;
    
        for(j=i+1;j<20; j++) {
            b=(bookA[j].getTitle().compareTo(bookA[minIndex].getTitle()));
            if(b<0){
                minIndex=j;
            }
        }
    
        Book temp = bookA[i];
        bookA[i] = bookA[minIndex];
        bookA[minIndex] = temp;
    }
    
    for(int z=0;z<20;z++)
        System.out.println(bookA[z].toString());