Professional Documents
Culture Documents
1. Arrays in Java
a. Create a public class NumberList which declares a field (named list) with type array of doubles. The array should be created by a constructor which is parameterized with the length of the array. Add a method print which prints the array as a sequence of numbers. [10 marks] b. Add to this class a method randomFill which fills the array in field list with pseudorandom numbers of type double. Hint: there is a Java API class for pseudo-random numbers. [10 marks] c. Add a method sort which sorts the array in field list using the algorithm on the next page. Add a public static main method and let it create an instance of class NumberList. Use the first argument of method main (converted to a number) as the argument for the constructor. Fill the list with random numbers, sort it, and finally print it using the methods created for the previous questions. Dont use any Java Collections Framework class or any of the build-in sort methods of the Java API. If you cannot implement the following algorithm, implement Quicksort instead. However, marks for question 1 c are capped at 15 then.
Sort algorithm to use (given in Python code note that your corresponding Java method shall neither return anything nor have any parameters):
def swap(array, i, j): array[i], array[j] = array[j], array[i] def sortarray(array): s = None
# Use arrays to implement array and s in Java for Q1, not a Collections class
ln = len(array) if ln == 0: return def sort_step(array, start, delta): for i in range(start+delta, ln, delta): j = i while j>start and cmp(array[j], array[j-delta])== -1: swap(array, j, j-delta) j -= delta if s == None: s = [] from math import log max = int(log(ln)/log(2))-1 while max > 1: s.append(2**max-1) max -= 1 s.append(1) for i in s: for j in range(i): sort_step(array, j, i)
[30 marks]
Furthermore, UniversalList should allow to store in the collection list objects of any class which implements interface Comparable (i.e., not just objects of class Double) and should have a new version of method sort which works with such list elements (making use of the method compareTo of interface Comparable). Hint: only a small number of simple modifications of class NumberList2 is required. Test your new program and make sure that it can still create, sort and print lists with random numbers. [20 marks]