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 f rst sorting the top n elements. By the induction hypothesis, this is done correctly. The f 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 elems 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

This note was uploaded on 12/27/2011 for the course MAP 2302 taught by Professor Bell,d during the Fall '08 term at UNF.

Ask a homework question - tutors are online