[英]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.