forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Count_Inversion.cpp (jainaman224#2625)
- Loading branch information
1 parent
32f017b
commit 225ddd0
Showing
1 changed file
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
// Count inversion using merge sort | ||
|
||
#include <iostream> | ||
using namespace std; | ||
|
||
//merge two sorted arrays such that resultant array is also sorted | ||
int merge(int array[], int aux[], int low, int mid, int high) | ||
{ | ||
int x = low, y = mid, z = low, count = 0; | ||
|
||
// checking till left and right half of merge sort | ||
while ((x <= mid-1) && (y <= high)) | ||
{ | ||
if (array[x] <= array[y]) | ||
{ | ||
aux[z++] = array[x++]; | ||
} | ||
else | ||
{ | ||
aux[z++] = array[y++]; | ||
count += mid-x; | ||
} | ||
} | ||
|
||
// Copy remaining elements | ||
while (x <= mid-1) | ||
{ | ||
aux[z++] = array[x++]; | ||
} | ||
|
||
while (y <= high) | ||
{ | ||
aux[z++] = array[y++]; | ||
} | ||
|
||
// Sorting the original array with the help of aux array | ||
for (int i = low; i <= high; i++) | ||
{ | ||
array[i] = aux[i]; | ||
} | ||
return count; | ||
} | ||
|
||
//merge sort to find inversion count | ||
int mergeSort(int array[], int aux[], int low, int high) | ||
{ | ||
int count = 0; | ||
if (high > low) | ||
{ | ||
int mid = (low + high) / 2; | ||
|
||
// merge sort on Left half of the array | ||
count = mergeSort(array, aux, low, mid); | ||
// merge sort on Right half of the array | ||
count += mergeSort(array, aux, mid + 1, high); | ||
// Merge the two half | ||
count += merge(array, aux, low, mid + 1, high); | ||
} | ||
return count; | ||
} | ||
|
||
//wrapper function that returns number of inversions | ||
int inversions_count(int array[], int n) | ||
{ | ||
int aux[n]; | ||
return mergeSort(array, aux, 0, n-1); | ||
} | ||
|
||
int main () | ||
{ | ||
int n; | ||
cin >> n; | ||
int arr[n]; | ||
for(int i = 0; i < n; i++) | ||
cin >> arr[i]; | ||
cout << (inversions_count(arr, n)) << endl; | ||
return 0; | ||
} | ||
|
||
/* Sample input | ||
5 | ||
1 20 6 4 5 | ||
Sample Output | ||
5 */ |