In an array, , the elements at indices and (where ) form an inversion if . In other words, inverted elements and are considered to be "out of order". To correct an inversion, we can swap adjacent elements.
Example
To sort the array, we must perform the following two swaps to correct the inversions:
The sort has two inversions: and .
Given an array , return the number of inversions to sort the array.
Function Description
Complete the function countInversions in the editor below.
countInversions has the following parameter(s):
int arr[n]: an array of integers to sort
Returns
int: the number of inversions
Ещё видео!