Homework # 7

Due: Oct. 29, 2004 (F)

As discussed in class, accessing an array element using indexing (e.g., numbers[i]) requires the compiler to generate code that does a multiplication and addition to calculate the address of

the element (where numbers[i] is located in memory). If your algorithm has a regular pattern of access (e.g., sequential access of elements), then you can use pointers and pointer arithmetic to "walk" a pointer through the array using just addition.

Compare the bubble sort code below using indexes vs. the bubble sort code using pointers.

void bubbleSortUsingIndex(int count, int * numbers) {

int lastUnsortedIndex;

int testIndex;

int temp;

for (lastUnsortedIndex = count-1; lastUnsortedIndex > 0;

lastUnsortedIndex--) {

for (testIndex = 0; testIndex < lastUnsortedIndex; testIndex++) {

if (numbers[testIndex] > numbers[testIndex+1]) {

temp = numbers[testIndex];

numbers[testIndex] = numbers[testIndex+1];

numbers[testIndex+1] = temp;

} /* end if */

} /* end for (testIndex */

} /* end for (lastUnsortedIndex */

} /* bubbleSortUsingIndex */

void bubbleSort(int count, int * numbers) {

int * lastUnsortedPtr;

int * testPtr;

int temp;

for (lastUnsortedPtr = numbers+(count-1); lastUnsortedPtr > numbers;

lastUnsortedPtr--) {

for (testPtr = numbers; testPtr < lastUnsortedPtr; testPtr++) {

if (*testPtr > *(testPtr+1)) {

temp = *testPtr;

*testPtr = *(testPtr+1);

*(testPtr+1) = temp;

} /* end if */

} /* end for (testPtr */

} /* end for (lastUnsortedPtr */

} /* bubbleSort */

The file bubbleSortPtrs.c at http://www.cs.uni.edu/~fienup/cs036f04/homework/bubbleSortPtrs.c

contains a program that times both versions of bubble sort using arrays of random numbers to see which is faster.

Your assignment is to copy the bubbleSortPtrs.c file and replace both versions of the bubble sort code by corresponding versions of the selection sort (i.e., one using indexes and one using pointers). A selection sort code using indexes is at http://www.cs.uni.edu/~fienup/cs036f04/homework/selectionSort.c

Again, use the Linux system to edit, compile, execute, and debug your programs.

To submit your assignment, click on the link at the bottom of the homework page for the course: http://www.cs.uni.edu/~fienup/cs036f04/homework/index.htm

You will need to

  1. log on to the submission system using your CNS account information
  2. select the "810:036, C++ Fienup" course
  3. select the radio button corresponding to lab being submitted
  4. enter the name of the file you wish to submit which needs to be accessable on the computer from which you are submitting