Inversion of Array
An inversion in an array refers to a pair of elements (a[i], a[j]) where i < j but a[i] > a[j]. The number of inversions quantifies how close an array is to being fully sorted.
Java example using merge sort:
|
|
C++ example using BST:
|
|
Python example using brute force:
|
|
Inversion count quantifies presortedness and aids in analyzing sorting algorithms.
Here are some ways to visualize and think about inversions in arrays:
- Graphical plot: Plot the array values on a number line. Inversions visually appear as crosses on the plot.
For [3, 2, 1, 5, 4]:
3 —-
\
2 –
1
5
4
Swap count: If you imagine bubble sort swapping adjacent inverted pairs, the number of swaps equals the inversion count.
Order violation: An inversion violates the sorted order of elements. Visualizing how many times an element appears before a smaller value aids understanding.
Distance from sorted: The inversion count provides a metric for how far an array is from sorted order. The higher the inversions, the more disordered the array is.
Tree visualization: For busted algorithms like merge sort, you can visualize splits and merges of the array on a tree, counting inversions at each merge.
The main idea is to visualize inverted pairs of out-of-order elements. Graphically marking violations of sorted order provides an intuition into counting and understanding inversions. These visual metaphors can help make an abstract concept more concrete.
Inversion in an array is a pair of indices (i, j)
such that i < j
but array[i] > array[j]
. In simpler terms, if an element at a lower index is greater than an element at a higher index, it’s considered an inversion. Inversions are a way to measure how far an array is from being sorted. A sorted array has zero inversions.
Let’s use the example array [8, 4, 2, 1]
to demonstrate how the number of inversions are counted in each iteration using the simple nested loop approach. The table describes the process:
Iteration | Element array[i] | Iterating array[j] | Is array[i] > array[j] ? | Count of Inversions |
---|---|---|---|---|
1 | 8 | 4 | Yes | 1 |
1 | 8 | 2 | Yes | 2 |
1 | 8 | 1 | Yes | 3 |
2 | 4 | 2 | Yes | 4 |
2 | 4 | 1 | Yes | 5 |
3 | 2 | 1 | Yes | 6 |
4 | 1 | - | - | 6 |
In this example, we start with an inversion count of 0 and loop through the array. At each iteration i
, we check the subsequent elements j
to see if they are smaller than array[i]
. If they are, we increment the count of inversions. By the end of all iterations, we have counted 6 inversions in the array [8, 4, 2, 1]
.
Java Code
Here’s how you can count the number of inversions in Java using a simple nested loop:
|
|
C++ Code
Similarly, in C++, you can count inversions using nested loops:
|
|
Python Code
In Python, you can achieve this with:
|
|
In these examples, we used a simple but inefficient method to count inversions, with a time complexity of O(n^2). More efficient algorithms, like using merge sort, can count inversions in O(n log n) time.