import java.util.Collections; import java.util.ArrayList; import java.util.Random; /** Array.java - do all the heavy lifting for the Randomized Quick Select * algorithm. Store the numbers from 1 to n. I think the implementation * is easier if we use ArrayList as the underlying representation of data. * The numbers will be shuffled using Java's built-in shuffler. * Then, to do the select algorithm, we assume we want the k-th SMALLEST * number, which should wind up being k. * For a given "Array" instance, you could use different values of k, * so I have decided not to declare k as an attribute of the class. * However, note that when we count operations, we need to start the count * over every time we begin a new select. * Since the RQS algorithm needs a random number generator, we'll just * make it an attribute of our "Array" as well. */ public class Array { private ArrayList S; private int ops; private Random gen; public Array(int size) { gen = new Random(); S = new ArrayList(); for (int i = 1; i <= size; ++i) S.add(new Integer(i)); Collections.shuffle(S); } /** A wrapper function to begin the Randomized Quick Select Algorithm. * Every time we begin a brand new select problem, we need to set the * number of counted operations to 0. */ public int rqs(int k) { ops = 2; // Call the recursive function. int result = quickSelect(S, k); return result; } /** This is the recursive function that performs the quickSelect() * function suggested by the class notes. Here's the pseudocode: * quickSelect(S, k): * if n = 1 * return S[1] * x = random element from S * L = [ all elements < x ] * E = [ all elements == x ] * G = [ all elements > x ] * if k <= |L| * return quickSelect(L,k) * else if k <= |L| + |E| * return x * else * return quickSelect(G, k - |L| - |E|) * // e.g. 12th out of 20 = 2nd out of 10 */ private int quickSelect(ArrayList listS, int k) { ////////////////////////////////////////////////////////// // Take out the return 0, and insert your implementation. ////////////////////////////////////////////////////////// return 0; } public int getOps() { return ops; } }