The above code, is used to perform an \"insertion sort\" on a linked list. How c
ID: 3713125 • Letter: T
Question
The above code, is used to perform an "insertion sort" on a linked list. How can it be modified to perform a "bubble sort" instead?
/ Perform an Insertion Sort int InsertionsortO 391 392 393 394 395 396 397 398 399 488 481 482 483 484 485 486 487 488 489 418 411 412 413 string strData; int iNodeCount e NodeClass tempNode int icompareCount e; bool swapfalse; // data from current node // count of nodes in list // temp node to point to current node // count list->SetcurrentNode (list->GetFirstNode)); // start at top of list while (list->GetCurrentNode) !-list->GetLastNode)) list->Next); list->SetcurrentNode (list->GetFirstNode)); list->Next); // start at top of list // start at 2nd node // single pass, through entire list // save address of current node for (int i-e; i GetcurrentNode ); strData -list->GetcurrentNode()->Getstring) // get data from temp node 415 416 417 418 419 428 swapfalse; // true if node needs to move // run backward till either match or // top of list /I count comparisons (went back "x times, now get back by going x" times forward.) // special treatment for top of list 422 icomparecount++; if (list->GetCurrentNode)list->GetFirstNode()) 426 swap true; else if (strData.compare( list->GetCurrentNode ()->GetPrevNode()->Getstring))1) 428 429 438 431 432 433 - true if (swap) 435 436 437 438 439 list-Insert (strData); list->SetCurrentNode (tempNode); list->Delete); tempNode list break; // insert here // reset location // delete the node we just moved // re-save temp location // end of backward crawl // back up one node list->Previous O; while (list->GetcurrentNode) ! nullptr); 443 II for loop list->SetcurrentNode (list->GetFirstNode)) done with sort, go back to top of list return icomparecount; 448Explanation / Answer
Solution:
Only the loop at line 412 needs to change which is deciding which node we need to swap.
Please note that bubble sort simply compares two adjacent elements and then swaps them if they are not in order.
change:
for (i = 0; i < inodeCount; i++)
if (list->GetCurrentNode() > list->GetCurrentNode()->GetNextNode())
swap= true;
else
swap= false;
}
the code in text was not provided so I have given the change which should be sone, please adjust the syntax accordingly, the logic will be the same.
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.