DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES
Count Array Inversions with Merge Sort
Learn how to count array inversions with merge sort using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Inversions = 3
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
long long merge_count(int values[], int temporary[], int left, int right)
{
if (left >= right) return 0;
int middle = left + (right - left) / 2;
long long count = merge_count(values, temporary, left, middle)
+ merge_count(values, temporary, middle + 1, right);
int first = left, second = middle + 1, write = left;
while (first <= middle && second <= right) {
if (values[first] <= values[second]) temporary[write++] = values[first++];
else {
temporary[write++] = values[second++];
count += middle - first + 1;
}
}
while (first <= middle) temporary[write++] = values[first++];
while (second <= right) temporary[write++] = values[second++];
for (int index = left; index <= right; index++) values[index] = temporary[index];
return count;
}
int main(void)
{
int values[] = {2, 4, 1, 3, 5};
int temporary[5];
long long inversions = merge_count(values, temporary, 0, 4);
printf("Inversions = %lld\n", inversions);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Inversions = 3
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- During merging, every right-side value chosen before remaining left values forms inversions.
- Display the computed result.
During merging, every right-side value chosen before remaining left values forms inversions.
EFFICIENCY
Time and space complexity
Time complexity
O(n log n)
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
