[英]How do I find the longest boat (length) by using bubble sort?
我正在处理该单例类(这是一艘船)的项目。 我正在从事一项活动,它将显示最长的船只。 我想尝试使用冒泡排序按最长船排序列表。 该应用程序运行,但是当我按下显示最长船的按钮时,它停止工作。 有人可以帮我吗?
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
这是一个无限循环,因为您无需修改found
, i
或循环内的列表大小:
while(!found && (i < boat_list.size()))
您的代码中不需要3个循环。 如果您只想要最长的船,请在船上进行一次迭代,并取其最大值。 如果要使用冒泡排序算法进行排序,则最大元素将在排序之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.