【问题标题】:How do I find the longest boat (length) by using bubble sort?如何使用冒泡排序找到最长的船(长度)?
【发布时间】:2015-06-01 00:30:38
【问题描述】:

我正在处理作为船列表的单例类的项目。我正在开展一项活动,该活动将展示最长的船。我想尝试使用冒泡排序按最长的船对列表进行排序。该应用程序运行,但是当我按下显示最长船的按钮时它停止工作。谁能帮帮我?

public void showLongBoat(View view)
{
    //Declare references
    BoatList boat_list;
    TextView tv;
    int i;
    int x = 0;
    boolean found;
    int num_items;
    int visit = 0;
    boolean exchange_value;
    int last_item;
    int temp;
    int a = 0;
    int b;

    //Set references. Access the list.
    boat_list = BoatList.getInstance();

    tv = (TextView) findViewById(R.id.text_main);

    //Get the number of items in the list
    num_items = boat_list.size();

    //Find the longest boat
    i = 0;
    found = false;

    while(!found && (i < boat_list.size()))
    {
        //If num_item is 0 or 1, then do not sort. Otherwise, do sorting
        if(num_items > 1)
        {
            //Set the number of values to visit on the first pass
            visit = num_items - 1;
        }

        do
        {
            //No exchange or swapping of item was made, so set the    exchange to false
            exchange_value = false;

            //Set the index for the last item to visit
            last_item = visit - 1;

            for(x = 0; x <= last_item; x++)
            {
                if(boat_list.get(x).getLength() > boat_list.get(x).getLength() + 1)
                {
                    //Swap the item
                    temp = a;
                    a = boat_list.get(x).getLength() + 1;
                    b = temp;

                    exchange_value = true;
                }
            }

            visit--;
        }while(exchange_value && (visit > 0)); //end sort
    }

    if(found)
    {
        boat_list.get(x).getLength();
        tv.append("Longest Boat is: ");
    }
    else
    {
        Toast.makeText(ShowLongBoatActivity.this, "Error: Cannot find the longest boat successfully!",
                Toast.LENGTH_SHORT).show();
    }

} //end of showLongBoat

【问题讨论】:

    标签: java android list sorting


    【解决方案1】:

    这是一个无限循环,因为您不修改 found,i 或循环内的列表大小:

    while(!found && (i < boat_list.size()))
    

    您的代码中不需要 3 个循环。如果您只想要最长的船,则对船进行一次迭代并取最大值就足够了。如果要进行排序,使用冒泡排序算法,排序后最大的元素会在最后。

    【讨论】:

    • 或者倒序排列,就在开头。
    • @DavidSN 谢谢。我摆脱了 while 循环,现在我有了 do while 循环和一个 for 循环,我用它来交换项目。
    猜你喜欢
    • 2016-02-09
    • 2021-12-30
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2021-03-24
    • 2017-10-20
    • 2020-04-14
    • 1970-01-01
    相关资源
    最近更新 更多