dev-resources.site
for different kinds of informations.
Merge Sort
Published at
7/4/2023
Categories
cpp
beginners
algorithms
mergesort
Author
Ankit Kumar Meena
Main Article
It is a sorting algorithm that follows the divide-and-conquer approach. It efficiently sorts an array or a list by dividing it into smaller sub-arrays, sorting them, and then merging them back together.
C++ Code
#include <bits/stdc++.h>
using namespace std;
void merge(int array[], int const left, int const mid, int const right){
int const subArrayOne = mid - left + 1;
int const subArrayTwo = right - mid;
auto *leftArray = new int[subArrayOne],
*rightArray = new int[subArrayTwo];
for (auto i = 0; i < subArrayOne; i++)
leftArray[i] = array[left + i];
for (auto j = 0; j < subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];
auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0;
int indexOfMergedArray = left;
while (indexOfSubArrayOne < subArrayOne
&& indexOfSubArrayTwo < subArrayTwo) {
if (leftArray[indexOfSubArrayOne]
<= rightArray[indexOfSubArrayTwo]) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}
while (indexOfSubArrayOne < subArrayOne) {
array[indexOfMergedArray]
= leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}
while (indexOfSubArrayTwo < subArrayTwo) {
array[indexOfMergedArray]
= rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
delete[] leftArray;
delete[] rightArray;
}
void mergeSort(int array[], int const begin, int const end)
{
if (begin >= end)
return;
int mid = begin + (end - begin) / 2;
mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}
void printArray(int A[], int size)
{
for (int i = 0; i < size; i++)
cout << A[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
cout << "Given array is \n";
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
cout << "\nSorted array is \n";
printArray(arr, arr_size);
return 0;
}
Articles
12 articles in total
Getting Started with Docker: A Guide for Developers
read article
Mastering Fragments in Java for Android Development
read article
Mastering RecyclerView in Java for Android Development
read article
Understanding Adapters in Java for Android Development
read article
My Journey in Android Development: Learning Java and Building Apps
read article
Merge Sort
currently reading
Selection Sort
read article
Bubble Sort
read article
Insertion Sort
read article
The Artistry of Front-End Development: Building Captivating User Experiences
read article
Demystifying Cloud Computing: A Comprehensive Guide
read article
Hi!
read article
Featured ones: