简体   繁体   English

冒泡排序没有排序

[英]Bubble sort didnt sort

I tried to do bubble sort and still a beginner, I didn't find any errors but when I tried to sort it alphabetically it didn't sort the array.我尝试进行冒泡排序,但仍然是初学者,我没有发现任何错误,但是当我尝试按字母顺序对其进行排序时,它没有对数组进行排序。

public class Main {公共课主要{

public static void bubblesort ( String [] name) {
    String tempmemory = " na";

    for (int i = 0; i < name.length; i++) {
        for (int j = 0; j < (name.length - 1); j++) {

            if (name[j].compareTo(name[j + 1]) < 0)

                tempmemory = name[j];
            name[j] = name[j + 1];
            name[j + 1] = tempmemory;
        }
    }
}

public static void main ( String [] args) {

    String [] name  = { "ciku", "eman","aina"} ;

    int i=0;

    System.out.println(" Before sort : ");
    while (i < name.length)
    {
        System.out.print ( name[i] + "  ");

        i++;
    }

    bubblesort(name);

    i=0;
    System.out.println(" \n After sort : ");
    while (i < name.length)
    {
        System.out.print ( name[i] + "  ");

        i++;
    }

} }

} }

Your if condition should include those 3 statements, right now it only have one statement under it ie tempmemory = name[j];.您的 if 条件应该包括这 3 个语句,现在它下面只有一个语句,即 tempmemory = name[j];。 So use {} bracket for if condition if it has multiple statement.所以如果条件有多个语句,请使用 {} 括号。 So write if statement like this:所以写这样的 if 语句:

if (name[j].compareTo(name[j + 1]) < 0) 
 { tempmemory = name[j];   
   name[j] = name[j + 1];
   name[j + 1] = tempmemory; }

This chunk of code:这块代码:

            if (name[j].compareTo(name[j + 1]) < 0)

                tempmemory = name[j];
            name[j] = name[j + 1];
            name[j + 1] = tempmemory;

is obviously wrong.显然是错误的。

Hint: use { and } to fix it.提示:使用{}修复它。

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

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