forked from tarunsinghofficial/HacktoberFest
-
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.
Merge pull request tarunsinghofficial#1795 from MdAnsar7/main
Add files via upload
- Loading branch information
Showing
1 changed file
with
78 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,78 @@ | ||
#include <bits/stdc++.h> | ||
using namespace std; | ||
int merge(int arr[], int low, int mid, int high) | ||
{ | ||
int i = low, j = mid + 1, k = low; | ||
int b[high]; | ||
int count=0; | ||
while (i <= mid && j <= high) | ||
{ | ||
if (arr[i] <= arr[j]) | ||
{ | ||
b[k] = arr[i]; | ||
i++; | ||
k++; | ||
} | ||
else | ||
{ | ||
b[k] = arr[j]; | ||
j++; | ||
k++; | ||
count+=mid+1-i; | ||
} | ||
} | ||
if (i > mid) | ||
{ | ||
while (j<=high) | ||
{ | ||
b[k]=arr[j]; | ||
j++; | ||
k++; | ||
} | ||
|
||
} | ||
else{ | ||
while (i<=mid) | ||
{ | ||
b[k]=arr[i]; | ||
i++; | ||
k++; | ||
} | ||
|
||
} | ||
for(k=low;k<=high;k++) | ||
arr[k]=b[k]; | ||
|
||
return count; | ||
} | ||
int mergesort(int arr[], int low, int high) | ||
{ | ||
int mid; | ||
int count = 0; | ||
if (high > low) | ||
{ | ||
mid = (high + low) / 2; | ||
count += mergesort(arr, low, mid); | ||
count += mergesort(arr, mid + 1, high); | ||
count += merge(arr, low, mid, high); | ||
} | ||
|
||
return count; | ||
} | ||
int main() | ||
{ | ||
|
||
int n; | ||
cout << "enter array length="; | ||
cin >> n; | ||
int arr[n]; | ||
cout << "\n enter array to be sorted="; | ||
for (int i = 0; i < n; i++) | ||
{ | ||
cin >> arr[i]; | ||
} | ||
|
||
cout << mergesort(arr, 0, n); | ||
cout << endl; | ||
return 0; | ||
} |