I am working on the project with handling a singleton class that is a list of boat. I am working on an activity that will show the longest boat. I want to try using bubble sort to sort the list by its longest boat. The app runs, but then it stop working when I press the button for showing the longest boat. Could anyone help me?
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
This is a infinite loop, as you don't modify found
, i
or the list size inside the loop:
while(!found && (i < boat_list.size()))
You don't need 3 loops in your code. If you only want the longest boat, iterate over the boats one time and take the maximum it's enough. If you want to make the sort, using a bubble sort algorithm, the biggest element will be at the end after sorting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.