Extra Credit Programming Assignment
Extra Credit Programming Assignment
1. Objective
Your goal is to write a program that will enable you to make use of mergesort to solve a seemingly
unrelated problem. [This is a common interview question. I too have been asked this one!]
2. Problem
You have been asked to find the number of inversions in an array. An inversion is when a larger number
appears before a smaller number. In the follow example, there are 3 inversions.
[3, 2, 1]
1. 3 before 2
2. 3 before 1
3. 2 before 1
You need to write two different algorithms to solve this problem. One is “slow”. It is the naïve approach
using nested loops. The “fast” approach uses a modified mergesort that counts the number of inversions
and returns that count. Your program will always run the fast algorithm unless the user specifies “slow”
as the (only) command-line argument.
$ java InversionCounter
Enter sequence of integers, each followed by a space: x 1 2 3
Error: Invalid character 'x' found at index 4 in input stream.
$ java InversionCounter
Enter sequence of integers, each followed by a space: <some spaces>
Error: Sequence of integers not received.
$ java InversionCounter
Enter sequence of integers, each followed by a space: 3 1 0 1 2 9
Number of inversions: 5
For large inputs, you should observe a drastic improvement in performance when you use the 𝜃𝜃(𝑛𝑛 lg 𝑛𝑛)
algorithm based off mergesort versus the 𝜃𝜃(𝑛𝑛2 ) solution with nested loops.
3. Requirements
You must use the mergesort algorithm given in class. Very few changes are required to make mergesort
count inversions. The code is provided below:
Inversions - 2
private static void mergesortHelper(int[] array, int[] scratch, int low, int high) {
if (low < high) {
int mid = low + (high - low) / 2;
mergesortHelper(array, scratch, low, mid);
mergesortHelper(array, scratch, mid + 1, high);
No credit will be given for solutions modifying any other implementation. For example, the merge
routine cannot be in a separate function, as is found in many implementations online. It is safe to say
that the lines of code below
must be present in your solution. The number of inversions for large inputs can exceed the max value of
an integer. Both methods should return a long.
You are allowed up to 8 seconds for the “slow” version and 1.25 seconds for the “fast” version. You
should have no trouble meeting these timing requirements.
Use the template file provided and test your work with the supplied test script.