Untitled
unknown
c_cpp
3 years ago
1.5 kB
2
Indexable
Never
#include <bits/stdc++.h> using namespace std; int merge(int arr[], int temp[], int left, int mid, int right) { int i, j, k; int inv_count = 0; i = left; j = mid; k = left; while ((i <= mid - 1) && (j <= right)) { if (arr[i] <= arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; inv_count = inv_count + (mid - i); } } while (i <= mid - 1) { temp[k++] = arr[i++]; } while (j <= right) { temp[k++] = arr[j++]; } for (i = left; i <= right; i++) { arr[i] = temp[i]; } return inv_count; } int mergeSort(int arr[], int temp[], int left, int right) { int mid; int cnt1 =0, cnt2 = 0, cnt3 =0; if (right > left) { mid = (right + left) / 2; cnt1 += mergeSort(arr, temp, left, mid); cnt2 += mergeSort(arr, temp, mid + 1, right); cnt3 += merge(arr, temp, left, mid + 1, right); } return (cnt1 + cnt2 + cnt3); } int inversionCount(int arr[], int array_size) { int temp[array_size]; return mergeSort(arr, temp, 0, array_size-1); } int main() { int arr[] = { 2,4,1,3,5}; int arr_size = sizeof(arr) / sizeof(arr[0]); int inversionCnt = inversionCount(arr, arr_size); cout<<" Number of inversions are: "<<inversionCnt; return 0; }