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

时间:2017-09-06 17:37:07

标签: java arrays string sorting bubble-sort

首先我要说的是,我知道有更好的方法来排序你可能会使用除数组之外的东西。这是一个类的赋值,用户可以在其中存储字符串,删除,显示和排序。我完全迷失了从这里去的地方。我试图使用冒泡排序,一切正常,除了我的数组中的第一个条目不会排序。我通过过滤掉空值来避免空指针异常,这就是我的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”, “赫尔普”,“山姆”。提前感谢您的指导。

4 个答案:

答案 0 :(得分: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 :(得分:1)

带有一些优化的Bubblesort算法:

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)

答案 2 :(得分: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

答案 3 :(得分: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));
相关问题