Count Inversions in an Array in Java

Yatin B.Yatin B.
1 min read

Date: 2025-01-10

This article explains how to count array inversions (pairs of elements where i < j and arr[i] > arr[j]). It presents two methods: a brute-force O(n²) approach and a more efficient O(n log n) divide-and-conquer method using merge sort. The brute-force method iterates through all pairs, while the optimized method recursively divides the array and counts inversions during merging. Both methods are illustrated with code examples, demonstrating how to calculate inversions and highlighting the performance difference between the approaches. For large datasets, the optimized method is significantly faster.

Read more

0
Subscribe to my newsletter

Read articles from Yatin B. directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yatin B.
Yatin B.