Skip to content

Commit a5e5f4d

Browse files
Updated
Added problem and comments in the code
1 parent 715afa8 commit a5e5f4d

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

04-Sorting/inversions.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
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+
*/
16
#include "bits/stdc++.h"
27
using namespace std;
38
void printArr(int arr[], int n,string s="\n"){
@@ -14,6 +19,7 @@ void printArr(int arr[], int n,string s="\n"){
1419
}
1520
}
1621
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
1723
int i=0,j=0,k = 0;
1824
int inversions = 0 ;
1925
while(i< leftLength && j<rightLength){
@@ -44,6 +50,7 @@ int merge(int left[], int right[], int arr[], int leftLength, int rightLength){
4450
return inversions;
4551
}
4652
int mergeSort(int arr[], int n){
53+
//the main merge sort function takes in array and the number of elements in the array
4754
int mid = n/2;
4855
if(n<2){
4956
return 0;
@@ -84,4 +91,4 @@ int main(){
8491
cout<< "Inversions are:"<< inversions(arr,8)<<endl;
8592
cout<< "Inversions output:"<< mergeSort(arr,8)<<endl;
8693
return 0;
87-
}
94+
}

0 commit comments

Comments
 (0)