CSci 280: Algorithms and problem-solving paradigms
Home Syllabus Classwork

printable version

Final Quiz

[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

Problem Fin.1.

[10 pts] Following is a poor implementation of merge sort in Java. In terms of n, the number of elements in the parameter ArrayList, how fast is it on a single processor? Provide the simplest and tightest big-O bound that you can, and justify your answer.

public static void mergeSort(ArrayList<Integer> nums) {
    if(nums.size() <= 1) return;

    ArrayList<Integer> a = new ArrayList<Integer>();
    ArrayList<Integer> b = new ArrayList<Integer>();
    for(int i = 0; i < nums.size(); i++) {
        if(i % 2 == 0) a.add(nums.get(i));
        else           b.add(nums.get(i));
    }
    
    mergeSort(a);
    mergeSort(b);
    
    nums.clear();
    while(!a.isEmpty() && !b.isEmpty()) {
        if(a.get(0).intValue() < b.get(0).intValue()) nums.add(a.remove(0));
        else                                          nums.add(b.remove(0));
    }
    nums.addAll(a);
    nums.addAll(b);
}