|
| 1 | +/* |
| 2 | +Count Inversions in an array using both the O(n^2) solution and using the optimised O(nlogn) solution. |
| 3 | +Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted, then the inversion count is 0, but if the array is sorted in the reverse order, the inversion count is the maximum. |
| 4 | +Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j |
| 5 | +*/ |
| 6 | +#include "bits/stdc++.h" |
| 7 | +using namespace std; |
| 8 | +void printArr(int arr[], int n,string s="\n"){ |
| 9 | + if(s==" "){ |
| 10 | + for(int i=0;i<n;i++){ |
| 11 | + cout<<arr[i]<<" "; |
| 12 | + } |
| 13 | + cout<<endl; |
| 14 | + } |
| 15 | + else{ |
| 16 | + for(int i=0;i<n;i++){ |
| 17 | + cout<<arr[i]<<'\n'; |
| 18 | + } |
| 19 | + } |
| 20 | + } |
| 21 | +int merge(int left[], int right[], int arr[], int leftLength, int rightLength){ |
| 22 | + //the helper function which helps to merge two arrays, left and right |
| 23 | + int i=0,j=0,k = 0; |
| 24 | + int inversions = 0 ; |
| 25 | + while(i< leftLength && j<rightLength){ |
| 26 | + if(left[i]<=right[j]){ |
| 27 | + arr[k]= left[i]; |
| 28 | + i++; |
| 29 | + k++; |
| 30 | + } |
| 31 | + else { |
| 32 | + arr[k] = right[j]; |
| 33 | + j++; |
| 34 | + k++; |
| 35 | + inversions += leftLength - i; |
| 36 | + } |
| 37 | + } |
| 38 | + while(i<leftLength){ |
| 39 | + arr[k] = left[i]; |
| 40 | + i++; |
| 41 | + k++; |
| 42 | + //inversions += rightLength; |
| 43 | + |
| 44 | + } |
| 45 | + while(j<rightLength){ |
| 46 | + arr[k] = right[j]; |
| 47 | + j++; |
| 48 | + k++; |
| 49 | + } |
| 50 | + return inversions; |
| 51 | +} |
| 52 | +int mergeSort(int arr[], int n){ |
| 53 | + //the main merge sort function takes in array and the number of elements in the array |
| 54 | + int mid = n/2; |
| 55 | + if(n<2){ |
| 56 | + return 0; |
| 57 | + } |
| 58 | + int left[mid]; |
| 59 | + int right[n-mid]; |
| 60 | + |
| 61 | + for(int i = 0 ; i<mid;i++){ |
| 62 | + left[i] = arr[i]; |
| 63 | + } |
| 64 | + //printArr(left, mid," "); |
| 65 | + int i = 0 ; |
| 66 | + for(int j = mid;j<n;j++){ |
| 67 | + right[i] = arr[j]; |
| 68 | + i++; |
| 69 | + } |
| 70 | + //printArr(right, n-mid," "); |
| 71 | + int x = mergeSort(left, mid); |
| 72 | + int y = mergeSort(right, n- mid); |
| 73 | + int z = merge(left, right, arr,mid, n- mid); |
| 74 | + |
| 75 | + return x+y+z; |
| 76 | + |
| 77 | +} |
| 78 | +int inversions(int arr[], int n){ |
| 79 | + int d = 0; |
| 80 | + for(int i = 0 ;i< n;i++){ |
| 81 | + for(int j = i+1;j<n;j++){ |
| 82 | + if(arr[i]>arr[j]){ |
| 83 | + d++; |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | +return d;} |
| 89 | +int main(){ |
| 90 | + int arr[8] = {2,1,4,6,7,5,3,8}; |
| 91 | + cout<< "Inversions are:"<< inversions(arr,8)<<endl; |
| 92 | + cout<< "Inversions output:"<< mergeSort(arr,8)<<endl; |
| 93 | + return 0; |
| 94 | +} |
0 commit comments