为什么我的冒泡排序不起作用? - Java

时间:2016-11-20 23:48:05

标签: 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.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;
            } 
        } 
    }

我认为问题与使用swap的行有关,因为在我使用此sortName()方法后打印arraylist时,所有内容都按相同顺序排列,尽管此行返回值大于0时本应该:

System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()));

1 个答案:

答案 0 :(得分:0)

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

    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
                } 
            } 
        }
相关问题