Skip to content

Commit cc00824

Browse files
committed
added mergesort algorithm implemented in c
1 parent a16b38d commit cc00824

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

merge.cpp

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

0 commit comments

Comments
 (0)