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

94 lines
1.4 KiB
C++
Raw Normal View History

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