{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Data Str & Algorithm HW Solutions 46

Data Str & Algorithm HW Solutions 46 - into the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
7 Internal Sorting 7.1 Base Case : For the list of one element, the double loop is not executed and the list is not processed. Thus, the list of one element remains unaltered and is sorted. Induction Hypothesis : Assume that the list of n elements is sorted correctly by Insertion Sort. Induction Step : The list of n + 1 elements is processed by fi rst sorting the top n elements. By the induction hypothesis, this is done correctly. The fi nal pass of the outer for loop will process the last element (call it X ). This is done by the inner for loop, which moves X up the list until a value smaller than that of X is encountered. At this point, X has been properly inserted
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: into the sorted list, leaving the entire collection of n + 1 elements correctly sorted. Thus, by the principle of Mathematical Induction, the theorem is correct. 7.2 void StackSort(AStack<int>& IN) { AStack<int> Temp1, Temp2; while (!IN.isEmpty()) // Transfer to another stack Temp1.push(IN.pop()); IN.push(Temp1.pop()); // Put back one element while (!Temp1.isEmpty()) { // Process rest of elems while (IN.top() > Temp1.top()) // Find elem’s place Temp2.push(IN.pop()); IN.push(Temp1.pop()); // Put the element in while (!Temp2.isEmpty()) // Put the rest back IN.push(Temp2.pop()); } } 46...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online