Java-使用compareTo()方法手动对字符串数组进行排序

问题描述 投票:1回答:4

首先我要说的是,我知道有更好的方法来排序您可能使用除数组之外的其他内容。这是一个类的赋值,用户可以在其中存储字符串,删除,显示和排序。我完全迷失了从这里去的地方。我试图使用冒泡排序,一切正常,除了我的数组中的第一个条目不会排序。我通过过滤掉空值来避免空指针异常,这就是我的if语句如此长的原因。

private void sortItems(String[] cargohold) {
    String temp;
    for (int i = 0; i < cargohold.length - 1; i++) {
        for (int j = 1; j < cargohold.length; j++) {
            if (cargohold[i] != null && cargohold[j] != null && (cargohold[i].compareTo(cargohold[j]) < 0)) {
                temp = cargohold[j];
                cargohold[j] = cargohold[i];
                cargohold[i] = temp;
            }   
        }
    }
}

我已经尝试了很多不同的方法来做到这一点,我找不到任何好的理由为什么这不起作用。我已经查看了Stack Overflow上可以找到的任何示例,并且没有人遇到同样的问题。

回顾一下,我可能有5个字符串,“Derp”,“Herp”,“Sam”,“Alfred”,“Bill”,这种情况会给我:“Derp”,“Alfred”,“Bill”,“Herp” ,“山姆”。提前感谢您的指导。

java arrays string sorting bubble-sort
4个回答
3
投票

这条线

if(cargohold[i] != null && cargohold[j] != null && (cargohold[i].compareTo(cargohold[j]) < 0))

应该

if(cargohold[j] != null && cargohold[j-1] != null && (cargohold[j].compareTo(cargohold[j-1]) < 0))

并且交换应该如下:

temp = cargohold[j];
cargohold[j] = cargohold[j-1];
cargohold[j-1] = temp;

请记住,在bubblesort中,您可以比较相邻的元素,而您的代码不会这样做。

缺陷

有些情况下,i > ji < j,但交换逻辑保持不变,这是完全错误的。


1
投票

具有一些优化的冒泡排序算法:

private static void sortItems(String cargohold[]) {
    String temp;
    boolean wasSwap = true;
    for (int index1 = 0; index1 < cargohold.length - 1 && wasSwap; ++index1) {
        wasSwap = false;
        for (int index2 = 0; index2 < cargohold.length - index1 - 1; ++index2) {
            if (cargohold[index2].compareToIgnoreCase(cargohold[index2+1]) > 0) {
                temp = cargohold[index2];
                cargohold[index2] = cargohold[index2+1];
                cargohold[index2+1] = temp;
                wasSwap = true;
            }
        }
    }
}

平均复杂性是O(n^2)O(n)的最佳情况。


0
投票

你的实现是错误的。

这是冒泡排序(以类似Java的简写):

for (index1 = 0; index1 < array.length - 1; ++index1)
    for (index2 = index1 + 1; index2 < array.length; ++index2)
        if (array[index1] < array[index1])
            swap(array[index1], array[index2]);

注意内部循环的index2 = index1 + 1。


0
投票
String[] str = { "red", "blue", "green" };
int n = str.length;
String temp;
System.out.println("Original String Array = " + Arrays.toString(str));
for(int a=0;a<n;a++) {
    for(int b=a+1;b<n;b++) {
        if( str[a].compareTo(str[b]) > 0 ) {
            temp = str[a];
            str[a] = str[b];
            str[b] = temp;
        }
    }
}
System.out.println("Sorted String Array = " + Arrays.toString(str));
© www.soinside.com 2019 - 2024. All rights reserved.