Skip to content

Commit eaa4d10

Browse files
author
Bhrigu Kansra
authored
Merge pull request #36 from ana301/master
added mergesort.
2 parents 71001bf + fbbd446 commit eaa4d10

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

contributors.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,7 @@
88
6. [Ujjval Patel](https://github.com/Ujjval-Patel)
99
7. [Shaguna Awasthi](https://github.com/Shagunaawasthi)
1010
8. [Joy Banerjee](https://github.com/joybanerjee08)
11-
9. [Kartikey Tripathi](https://github.com/kartikeytripathi)
11+
9. [Nikhil Arora](https://github.com/nikhilarora068)
12+
10. [Ambika](https://github.com/Ambika55)
13+
11. [Kartikey Tripathi](https://github.com/kartikeytripathi)
14+
12. [Ananya Keshari](https://github.com/ana301)

sorting/mergesort.cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
3+
void merge(int arr[], int l, int m, int r)
4+
{
5+
int i, j, k;
6+
int n1 = m - l + 1;
7+
int n2 = r - m;
8+
9+
int L[n1], R[n2];
10+
11+
for (i = 0; i < n1; i++)
12+
L[i] = arr[l + i];
13+
for (j = 0; j < n2; j++)
14+
R[j] = arr[m + 1+ j];
15+
16+
i = 0; // Initial index of first subarray
17+
j = 0; // Initial index of second subarray
18+
k = l; // Initial index of merged subarray
19+
while (i < n1 && j < n2)
20+
{
21+
if (L[i] <= R[j])
22+
{
23+
arr[k] = L[i];
24+
i++;
25+
}
26+
else
27+
{
28+
arr[k] = R[j];
29+
j++;
30+
}
31+
k++;
32+
}
33+
34+
35+
while (i < n1)
36+
{
37+
arr[k] = L[i];
38+
i++;
39+
k++;
40+
}
41+
42+
43+
while (j < n2)
44+
{
45+
arr[k] = R[j];
46+
j++;
47+
k++;
48+
}
49+
}
50+
{
51+
if (l < r)
52+
{
53+
// Same as (l+r)/2, but avoids overflow for
54+
// large l and h
55+
int m = l+(r-l)/2;
56+
57+
// Sort first and second halves
58+
mergeSort(arr, l, m);
59+
mergeSort(arr, m+1, r);
60+
61+
merge(arr, l, m, r);
62+
}
63+
}

0 commit comments

Comments
 (0)