Customer is #3 from the from the 2006 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/apc/_ap06_frq_computer_sc_51649.pdf

Part (a) compareCustomer method

public int compareCustomer(Customer other)
{
    if(getName().equals(other.getName()))
        return getID() - other.getID();

    return getName().compareTo(other.getName());
}

This method behaves nearly identically to the String compareTo method. See compareTo on the AP CS A Exam for additional information. (It also behaves similarly to the compareTo methods in many other classes; however, those are no longer tested on the AP CS A Exam.)

Part (b) prefixMerge method

public static void prefixMerge(Customer[] list1, Customer[] list2, Customer[] result)
{
    int list1Index = 0;
    int list2Index = 0;

    for(int resultIndex = 0; resultIndex < result.length; resultIndex++)
    {
        if(list1[list1Index].compareCustomer(list2[list2Index]) < 0)
        {
            result[resultIndex] = list1[list1Index];
            list1Index++;
        }
        else if(list1[list1Index].compareCustomer(list2[list2Index]) > 0)
        {
            result[resultIndex] = list2[list2Index];
            list2Index++;
        }
        else // duplicate (add one and skip both)
        {
            result[resultIndex] = list1[list1Index];
            list1Index++;
            list2Index++;
        }
    }
}

As mentioned in the question, prefixMerge is a simplified version of the merge method of merge sort. result.length is guaranteed to be <= list1.length and list2.length. This means that it is not necessary to check that list1Index and list2Index are valid in list1 and list2, respectively. Much of the code in merge exists to handle the elements remaining after all necessary comparisons.

2006 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Customer