COM1201 Spring 1997 Professor Fell QUIZ 5 Solution

1(7 points) Sort the array
37651482
using Insertion Sort . Show the results after each pass in the table below. Explain, briefly, what happened next to each row.
01234567index     
37651482original array           
376514827 left in position 1
367514826 moved before 7
356714825 moved before 6
135674821 moved before 3
134567824 moved before 5
134567828 left in place
123456782 moved before 3

2(6 points) Write a recursive function

	int S(int A[], int size)

that returns the sum of
A[0] + A[1] + A[2] + . . . + A[size - 1].

int S(int A[], int size){
// precondition:  size >= 1; A has at least size values
	if (size == 1) return A[0];
	return A[size - 1] + S(A, size -1);
}
3(7 points) The idea of the partition in QuickSort is:

  • Define M = (Lower + Upper) / 2.
  • Set X = A[M].
  • Initialize indices I = Lower and J = Upper.
  • Run a main loop while I ² J:

    A. Run a subloop to increase I until a large element is found
    B. Run a subloop to decrease J until a small element is found
    C. If it happens that I ² J after steps A and B then:

    Show the work of the partition function on the array below.

    a.	M = 3
    
    b.	X = 5
    
    c.	Show the contents of the array after each swap
    
    d.	What are the values of I and J when the partition is finished?
    J = 3
    I = 4

    01234567index     
    37651482original array           
    32651487I = 1, J = 7
    7 and 2 are swapped
    32451687I = 2, J = 5
    6 and 4 are swapped
    32415687I = 3, J = 4
    5 and 1 are swapped


    Last Updated: May 6, 1997 7:50 am by

    Harriet Fell
    College of Computer Science, Northeastern University
    360 Huntington Avenue #161CN,
    Boston, MA 02115
    Internet: fell@ccs.neu.edu
    Phone: (617) 373-2198 / Fax: (617) 373-5121
    The URL for this document is: http://www.ccs.neu.edu/home/fell/COM1101/QUIZ/Q5/quiz5.html