

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Assignment; Professor: Budd; Class: DATA STRUCTURES; Subject: Computer Science; University: Oregon State University; Term: Winter 2009;
Typology: Assignments
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Worksheet 7: Selection Sort and Program Proofs Name:
In preparation : Read Chapter 3 to learn more about debugging, testing and program proofs. In Chapter 3 you encountered a number of sorting algorithms. In this lesson you will investigate yet another algorithm, this one more useful in practical situations than either bubble or selection sort. The insertion sort algorithm is most easily described by considering a point in the middle of execution: Let p represent an index position in the middle of an array. The invariant you want to establish is that t this point the elements to the left of p (those with index values smaller than p) have already been sorted. Those to the right of p are completely unknown. The immediate task is simply to place the one element that is found at location p so that it, too, will be part of the sorted portion. To do this, the value at location p is compared to its neighbor. If it is smaller, it is swapped with its neighbor. It is then compared with the next element, possibly swapped, and so on. This process continues until one of two conditions occur. Either a value is found that is smaller, and so the ordering is established, or the value is swapped clear to the start of the array.
Worksheet 7: Selection Sort and Program Proofs Name:
All this can be done with a simple while loop. Assume the array is named data and contains double values. You can assume a routine swap that will exchange two data values. Write the while loop in the space below. To make this into a sorting algorithm we simply advance the value p through the entire array. The following example illustrates this: void insertionSort (double data [ ], int n) { int p, i; p = 1; /* invariants: all values with index positions less than p are sorted / while (p < n) { / your code here / / invariant is true here / p++; } / invariant is true here */ } Place your while loop into the code shown above, and then argue why the invariant is true at each of the locations shown.