Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么赢了';我的泡泡排序不行吗JAVA_Java_Sorting_Arraylist_Bubble Sort - Fatal编程技术网

为什么赢了';我的泡泡排序不行吗JAVA

为什么赢了';我的泡泡排序不行吗JAVA,java,sorting,arraylist,bubble-sort,Java,Sorting,Arraylist,Bubble Sort,我试图按对象的变量“name”对对象的arraylist进行字母排序。以下是我为此编写的代码: public void sortName() { int j; for ( j = 0; j < theBatters.size()-1; j++) { System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.g

我试图按对象的变量“name”对对象的arraylist进行字母排序。以下是我为此编写的代码:

public void sortName()
    {
        int j;

        for ( j = 0;  j < theBatters.size()-1;  j++)
        {
            System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()));
            if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j).getName()) > 0 )
            {                                             // ascending sort
                Collections.swap(theBatters, j, j+1);
                j=0;
            } 
        } 
    }

冒泡排序的名称本身就意味着存在已排序和未排序项目的冒泡。你只是忘记了这个事实。以下是工作(我希望)代码:

public void sortName()
{
对于(inti=0;i0)
{//升序排序
集合交换(theBatters,i,j);
//j=0;//没有必要,也不容易理解。它已经处于良好状态
} 
} 
}

在if语句中,为什么要再次比较get(j)和get(j)?@AndrewtheProgrammer发现了错误。你想在
compareToIgnoreCase
方法中的
if
语句中使用
the batter.get(j+1)
。很高兴我能帮上忙,我知道这样简单的错误很难从脸上看出来,Palm这样一个白痴哈哈,谢谢你,因为你在比较同一个对象的名称,所以没有做。打印比较结果时,使用的是
get(j)
get(j+1)
,但在
if
中,使用的是
get(j)
两次。您可能面临的另一个问题是在迭代结束时将
j
设置为
0
。但是在每次迭代之后,将执行
j++
,因此在下一次迭代开始时,您的
j
将变为
1
。考虑一下。
System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()));
    public void sortName()
        {

            for ( int i = 0;  i < theBatters.size()-1;  i++) // bigger outer bubble
            for ( int j = i+1;  j < theBatters.size()-1;  j++) // smaller inner bubble
            {                   System.out.println(theBatters.get(i).getName().compareToIgnoreCase(theBatters.get(j).getName()));
                if ( theBatters.get(i).getName().compareToIgnoreCase(theBatters.get(j).getName()) > 0 )
                {                                             // ascending sort
                    Collections.swap(theBatters, i, j);
                    // j=0; // Not necessary and confusing. It is already in good order
                } 
            } 
        }