Merging Algorithm
- Take an array (eg: a[] = {2, 53, 30,45, 44, 56, 12, 10}). Divide in 2 parts and sort them.
- Take i and j pointer and point at the 1st element of both parts.
2 30 45 56 | 10 12 44 53 i j
- Compare i and j, which ever is smaller, select that element and put that element in another array. The pointer in which the element was selected is moved ahead. In this example, 2 will be selected as it is smaller. So, 2 will be sent to another array and i will be moved to select 30.
2 30 45 56 | 10 12 44 53 i j
- Now compare i and j again. Now 10 will be selected so, append the another array which has 2 already in it with 10 and move the j to next value that is 12.
2 30 45 56 | 10 12 44 53 i j
- Repeat the process till last element
Apply this algorithm in your own code. Voila!
Merge Sort
merge_sort(a,i,j) {
if (i==j)
return a[i];
else {
mid = ((i+j)/2);
merge_sort(a,i,mid); // for left structure
merge_sort(a, mid+1, j); //for right structure
merging(a, i, mid, mid + 1, j);
}
}
Language: C++
#include <iostream>
using namespace std;
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays L[] and R[]
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge the temporary arrays back into arr[left..right]
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
// Sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
mergeSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:
Enter 5 elements: 4 20 18 2 55
Sorted array: 2 4 8 20 55
Videos to be referenced
Video 1:
Video 2: