0
can anyone explain me the BUBBLE SORT algorithm?
why there are 2 loops? for what?
4 Answers
+ 1
you use the outer loop as a flag to determine if the list or whatever is in order or not. Then you go through your list and compare the first item (let's call it 'a') to the second (let's call it 'b'), if a > b, swap a and b's position in the list and then compare it to the next item in the list, continue until the item is not greater than the next item in the list (that's where the second loop comes in)
like
void bubSort (int item[], int numItemsInArray)
{
int index =0;
bool orderOccurred == true;
while ( orderOccurred == true )
{
orderOccurred == false;
/* I usually do this first because if orderOccurred fails the next statements, it will end the outer while loop*/
for( index =0; index < numItemsInArray; index ++)
{
if( item [index] < item [index +1])
{
swap(item [index],item [index +1]);
//the above will replace the values with the other
orderOccurred = true;
//since a swap did occur, we set orderOccurred to true, then we will keep running through the whole array
}
}
}
}
Does that help? Feel free to ask questions, I'm here to help
+ 1
for and while loops are pretty similar to each other. I used a while here because I think it is simpler for readability. also, for loops are typically used for incrementing or iterative statement (like checking every item in a list or an array), but the core concept of the bubble sort is that the algorithm will start at the beginning of the list and try to make it through the whole list without having to swap any items (the end state of the algorithm is that the list is in order, so the algorithm will say did a swap occur is false when the list is in order). if a swap did occur, then the list was not in order and needs to be looked through again to see if the swap that happened put the list in order. I would recommend creating a list of like 5 random numbers and stepping through the process to order those random numbers in the list. Remember a swap will replace the numbers you input in the list. so say your first number is list [0] =5 and the second number is list [1] =3, swap(list [0],list [1]) will result in list [0]=3 and list [1]=5. Did that help?
0
why do you use the WHILE loop? i saw only FOR bubble sort. actually, it helped a bit, but i still can't get it
0
yes! thank you!