简体   繁体   English

Java:选择String类数组

[英]Java: Selection sort of String array

I am working on some sort algorithms for a school project and i have a problem . 我正在研究学校项目的一些排序算法,我有一个问题。 The following code its not sorting the array,I have tried the same code with array of numbers(the only change is in the if) and it was working but now with the String array and the use of compareTo its not working its just puts the items in "random" order. 下面的代码没有对数组进行排序,我尝试了相同的代码与数组(唯一的变化是在if中)并且它正在工作但是现在使用String数组并且使用compareTo它不能正常工作它只是放入“随机”顺序的项目。

public static void selectionSortISBN(Book pin[], int booksCounter) {
    for (int x = 0; x < booksCounter; x++) {
        int minIndex = x;
        for (int y = x + 1; y < booksCounter; y++) {
            if (pin[y].getISBN().compareTo(pin[minIndex].getISBN()) < 0) {
                minIndex = y;
            }
        }
        Book temp = pin[x];
        pin[x] = pin[minIndex];
        pin[minIndex] = temp;
    }
}

EDIT: 编辑:

I changed my inner for to this : 我改变了我的内心为此:

        for (int y = x + 1; y < booksCounter; y++) {
            int com=pin[y].getISBN().compareTo(pin[minIndex].getISBN());
            System.out.println(pin[y].getISBN()+"   "+pin[minIndex].getISBN()+"  =   "+com);
        }

and the output i am getting is this 我得到的输出就是这个

1537   1485  =   1
596   1485  =   4
1164   1485  =   -3
909   1485  =   8
596   1537  =   4
1164   1537  =   -4
909   1537  =   8
1164   596  =   -4
909   596  =   4
909   1164  =   8

This is working correctly, the mistake you are making is that you expect "596" to be under "1485", when it is not, you are sorting them as strings, 596 > 1485 just like BA > AAAABA. 这是正常的,你所犯的错误是你希望“596”低于“1485”,当它不是时,你将它们排序为字符串,596> 1485就像BA> AAAABA。 Add leading zeroes if you want to compare numbers alphanumerically. 如果要按字母数字比较数字,请添加前导零。

如果只处理数字,则将字符串数组转换为数字数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM