Skip to content

Commit a58219a

Browse files
Merge pull request #278 from tnmyk/main
Added Merge Sort
2 parents f42b416 + 25479a6 commit a58219a

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
void swapping(int &a, int &b) {
5+
int temp;
6+
temp = a;
7+
a = b;
8+
b = temp;
9+
}
10+
void display(int *array, int size) {
11+
for(int i = 0; i<size; i++)
12+
cout << array[i] << " ";
13+
cout << endl;
14+
}
15+
void merge(int *array, int l, int m, int r) {
16+
int i, j, k, nl, nr;
17+
//size of left and right sub-arrays
18+
nl = m-l+1; nr = r-m;
19+
int larr[nl], rarr[nr];
20+
//fill left and right sub-arrays
21+
for(i = 0; i<nl; i++)
22+
larr[i] = array[l+i];
23+
for(j = 0; j<nr; j++)
24+
rarr[j] = array[m+1+j];
25+
i = 0; j = 0; k = l;
26+
//marge temp arrays to real array
27+
while(i < nl && j<nr) {
28+
if(larr[i] <= rarr[j]) {
29+
array[k] = larr[i];
30+
i++;
31+
}else{
32+
array[k] = rarr[j];
33+
j++;
34+
}
35+
k++;
36+
}
37+
while(i<nl) { //extra element in left array
38+
array[k] = larr[i];
39+
i++; k++;
40+
}
41+
while(j<nr) { //extra element in right array
42+
array[k] = rarr[j];
43+
j++; k++;
44+
}
45+
}
46+
void mergeSort(int *array, int l, int r) {
47+
int m;
48+
if(l < r) {
49+
int m = l+(r-l)/2;
50+
// Sort first array
51+
mergeSort(array, l, m);
52+
// Sort second array
53+
mergeSort(array, m+1, r);
54+
55+
// merge both
56+
merge(array, l, m, r);
57+
}
58+
}
59+
int main() {
60+
int n;
61+
cin >> n; // Number of elements in array
62+
int arr[n];
63+
for(int i = 0; i<n; i++) {
64+
cin >> arr[i]; // Inputting elements into array.
65+
}
66+
mergeSort(arr, 0, n-1); // r = n-1 for last index
67+
cout << "Sorted Array";
68+
display(arr, n);
69+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Merge Sort
2+
Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
3+
4+
It recursively divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.
5+
6+
Time Complexity is O(nlogn).

0 commit comments

Comments
 (0)