Skip to content

Commit 91cecaa

Browse files
authored
Merge pull request #41 from RaviTejaCMS/master
Added Merge Sort
2 parents 1dfc98c + 1609e47 commit 91cecaa

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

SortingAlgos/C++/Merge Sort.cpp

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
/* C program for Merge Sort */
2+
// https://www.geeksforgeeks.org/merge-sort/
3+
#include<stdlib.h>
4+
#include<stdio.h>
5+
6+
// Merges two subarrays of arr[].
7+
// First subarray is arr[l..m]
8+
// Second subarray is arr[m+1..r]
9+
void merge(int arr[], int l, int m, int r)
10+
{
11+
int i, j, k;
12+
int n1 = m - l + 1;
13+
int n2 = r - m;
14+
15+
/* create temp arrays */
16+
int L[n1], R[n2];
17+
18+
/* Copy data to temp arrays L[] and R[] */
19+
for (i = 0; i < n1; i++)
20+
L[i] = arr[l + i];
21+
for (j = 0; j < n2; j++)
22+
R[j] = arr[m + 1+ j];
23+
24+
/* Merge the temp arrays back into arr[l..r]*/
25+
i = 0; // Initial index of first subarray
26+
j = 0; // Initial index of second subarray
27+
k = l; // Initial index of merged subarray
28+
while (i < n1 && j < n2)
29+
{
30+
if (L[i] <= R[j])
31+
{
32+
arr[k] = L[i];
33+
i++;
34+
}
35+
else
36+
{
37+
arr[k] = R[j];
38+
j++;
39+
}
40+
k++;
41+
}
42+
43+
/* Copy the remaining elements of L[], if there
44+
are any */
45+
while (i < n1)
46+
{
47+
arr[k] = L[i];
48+
i++;
49+
k++;
50+
}
51+
52+
/* Copy the remaining elements of R[], if there
53+
are any */
54+
while (j < n2)
55+
{
56+
arr[k] = R[j];
57+
j++;
58+
k++;
59+
}
60+
}
61+
62+
/* l is for left index and r is right index of the
63+
sub-array of arr to be sorted */
64+
void mergeSort(int arr[], int l, int r)
65+
{
66+
if (l < r)
67+
{
68+
// Same as (l+r)/2, but avoids overflow for
69+
// large l and h
70+
int m = l+(r-l)/2;
71+
72+
// Sort first and second halves
73+
mergeSort(arr, l, m);
74+
mergeSort(arr, m+1, r);
75+
76+
merge(arr, l, m, r);
77+
}
78+
}
79+
80+
/* UTILITY FUNCTIONS */
81+
/* Function to print an array */
82+
void printArray(int A[], int size)
83+
{
84+
int i;
85+
for (i=0; i < size; i++)
86+
printf("%d ", A[i]);
87+
printf("\n");
88+
}
89+
90+
/* Driver program to test above functions */
91+
int main()
92+
{
93+
int arr[] = {12, 11, 13, 5, 6, 7};
94+
int arr_size = sizeof(arr)/sizeof(arr[0]);
95+
96+
printf("Given array is \n");
97+
printArray(arr, arr_size);
98+
99+
mergeSort(arr, 0, arr_size - 1);
100+
101+
printf("\nSorted array is \n");
102+
printArray(arr, arr_size);
103+
return 0;
104+
}

0 commit comments

Comments
 (0)