CMPU 125 - Assignment 4 Recursion |
Assigned : Fri, Sep 26 Due
|
IMPORTANT: Read through the entire assignment write-up before starting to code your solution.
In this assignment you will:
Summary: You will implement a recursive method that returns the kth-smallest element of an array of integers. The algorithm you will implement recursively partitions an array, as described on pp. 148-152 of the text, until the partitioned element is in the kth position of the array (note: the kth element of a Java array is at index k-1).
Create
a folder called HW4. For this assignment, as in the last lab, you
should create a public static method in a class called HW4.java. You
will run and test your kSmall method from the interactions pane
initially, and later create a main method in a tester class to run the
program (using the Run button.)
You will implement the following method:
public static int kSmall(int k, int[] anArray, int first, int last)
To implement your kSmall method, you will follow the algorithm given in the text at the end of Section 3.3, pp. 148-152. In particular, you should reread the end of Section 3.3 in the text, and be sure you understand the recursive solution described. The high level solution given proceeds as follows:
kSmall()
method
is correctly implemented and tested in the interactions pane, create a
TestHW4.java file in which you create arrays and test the results of
using the kSmall method on those arrays. You should test at least
10 different arrays in your tester class (you may choose to generate
the contents using a pseudo-random number generator.) The only method
needed in the TestHW4 class is main. You do not need to instantiate any
objects of type HW4 because you can call the kSmall method through the
class name (HW4) exactly as you did in the interactions pane. You
should create tests that produce output like that shown below (of
course, you will have diferent random numbers...).====================================================================
Array before calling kSmall(11, ...):
[ -31 77 -46 15 -97 60 -64 -76 75 -71 92 -58 -31 -90 -54 ]
Array after calling kSmall(11, ...):
[ -54 -46 -97 -64 -76 -71 -58 -31 -90 -31 15 60 77 75 92 ]
kth smallest number = 15
Notice that in the example above, the 11th smallest number is 15, and that the array after calling kSmall()
is correctly partitioned around the location where 15 is stored.
kSmall()
method is working properly, you are almost ready to submit your project.Save both the HW4.java and TestHW4.java files in the HW4 folder. From a terminal window, type the following commands:
cd
cd cs125
submit125 HW4