TheAlgorithms-C-Plus-Plus/sorting/merge_sort.cpp

94 lines
1.3 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
2016-09-06 16:54:21 +08:00
using namespace std;
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
2019-08-21 10:10:08 +08:00
int n2 = r - m;
2016-09-06 16:54:21 +08:00
int L[n1], R[n2];
2019-08-21 10:10:08 +08:00
2016-09-06 16:54:21 +08:00
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
2019-08-21 10:10:08 +08:00
R[j] = arr[m + 1 + j];
2016-09-06 16:54:21 +08:00
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
2019-08-21 10:10:08 +08:00
2016-09-06 16:54:21 +08:00
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
2019-08-21 10:10:08 +08:00
int m = l + (r - l) / 2;
2016-09-06 16:54:21 +08:00
mergeSort(arr, l, m);
2019-08-21 10:10:08 +08:00
mergeSort(arr, m + 1, r);
2016-09-06 16:54:21 +08:00
merge(arr, l, m, r);
}
}
void show(int A[], int size)
{
int i;
2019-08-21 10:10:08 +08:00
for (i = 0; i < size; i++)
cout << A[i] << "\n";
2016-09-06 16:54:21 +08:00
}
int main()
{
2019-08-21 10:10:08 +08:00
int size;
cout << "\nEnter the number of elements : ";
2016-09-06 16:54:21 +08:00
2019-08-21 10:10:08 +08:00
cin >> size;
2016-09-06 16:54:21 +08:00
int arr[size];
2019-08-21 10:10:08 +08:00
cout << "\nEnter the unsorted elements : ";
2016-09-06 16:54:21 +08:00
for (int i = 0; i < size; ++i)
{
2019-08-21 10:10:08 +08:00
cout << "\n";
cin >> arr[i];
2016-09-06 16:54:21 +08:00
}
mergeSort(arr, 0, size);
2019-08-21 10:10:08 +08:00
cout << "Sorted array\n";
2016-09-06 16:54:21 +08:00
show(arr, size);
return 0;
}