THINK FIRST·CODE LATER

← All labs

Merge sort with a comparison counter

Problem

Implement top-down merge sort on an int array and count its work.

Input: an integer n (n ≥ 0), followed by n integers.

Algorithm (follow it exactly, so the counts match):

  • mergeSort(lo, hi) returns immediately if lo >= hi; otherwise mid = (lo + hi) / 2, sort lo..mid, sort mid+1..hi, then merge.
  • The merge compares the front elements with a[i] <= a[j] (taking from the left half on ties). Every evaluation of this test counts as one comparison. Copying the leftover elements of a half costs no comparisons.
  • Every call of merge counts as one merge.

Output: three lines. For the input 6 / 5 2 4 6 1 3:

Sorted: [1, 2, 3, 4, 5, 6]
Comparisons: 11
Merges: 5

Use Arrays.toString for the first line; an empty array prints Sorted: [].

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d9-1-data-1.txt

6
5 2 4 6 1 3
What your program must print for d9-1-data-1.txt
Sorted: [1, 2, 3, 4, 5, 6]
Comparisons: 11
Merges: 5

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d9-1-data-1.txt

Windows PowerShell does not understand <:

Get-Content d9-1-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.