12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

272 Chap. 7 Internal Sorting7.11 Exercises7.1 Using induction, prove that Insertion Sort will always produce a sorted array.7.2 Write an Insertion Sort algorithm for integer key values. However, here’sthe catch: The input is a stack (not an array), <strong>and</strong> the only variables thatyour algorithm may use are a fixed number of integers <strong>and</strong> a fixed number ofstacks. The algorithm should return a stack containing the records in sortedorder (with the least value being at the <strong>to</strong>p of the stack). Your algorithmshould be Θ(n 2 ) in the worst case.7.3 The Bubble Sort implementation has the following inner for loop:for (int j=n-1; j>i; j--)Consider the effect of replacing this with the following statement:for (int j=n-1; j>0; j--)Would the new implementation work correctly? Would the change affect theasymp<strong>to</strong>tic complexity of the algorithm? How would the change affect therunning time of the algorithm?7.4 When implementing Insertion Sort, a binary search could be used <strong>to</strong> locatethe position within the first i − 1 elements of the array in<strong>to</strong> which elementi should be inserted. How would this affect the number of comparisons required?How would using such a binary search affect the asymp<strong>to</strong>tic runningtime for Insertion Sort?7.5 Figure 7.5 shows the best-case number of swaps for Selection Sort as Θ(n).This is because the algorithm does not check <strong>to</strong> see if the ith record is alreadyin the ith position; that is, it might perform unnecessary swaps.(a) Modify the algorithm so that it does not make unnecessary swaps.(b) What is your prediction regarding whether this modification actuallyimproves the running time?(c) Write two programs <strong>to</strong> compare the actual running times of the originalSelection Sort <strong>and</strong> the modified algorithm. Which one is actuallyfaster?7.6 Recall that a sorting algorithm is said <strong>to</strong> be stable if the original ordering forduplicate keys is preserved. Of the sorting algorithms Insertion Sort, BubbleSort, Selection Sort, Shellsort, Quicksort, Mergesort, Heapsort, Binsort,<strong>and</strong> Radix Sort, which of these are stable, <strong>and</strong> which are not? For each one,describe either why it is or is not stable. If a minor change <strong>to</strong> the implementationwould make it stable, describe the change.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!