THINK FIRST·CODE LATER

← All labs

Counting inversions with merge sort

Problem

An inversion in an array is a pair of positions i < j with a[i] > a[j] (equal values are not an inversion). Write a program that counts the inversions of an array in O(n log n) time by modifying merge sort: the count is (inversions in the left half) + (inversions in the right half) + (split inversions counted during the merge).

Input. The first line holds n (0 ≤ n ≤ 200 000). The second line holds n integers.

Output. One line:

Inversions: X

Example. For the input

5
2 4 1 3 5

the output is

Inversions: 3

(the pairs 2 > 1, 4 > 1 and 4 > 3).

Use a long for the count: a reversed array of 200 000 elements has almost 2·10¹⁰ inversions. An O(n²) double loop is too slow for the largest inputs.

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.

d7-2-data-1.txt

5
2 4 1 3 5
What your program must print for d7-2-data-1.txt
Inversions: 3

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 < d7-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content d7-2-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.