Skip to content

Commit ce3f2cc

Browse files
authored
Add files via upload
1 parent c2c5864 commit ce3f2cc

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed
+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#include<stdio.h>
2+
3+
void Merge(int A[], int l, int mid, int h) // this is for two array inside one array
4+
{
5+
int i = l, j = mid + 1, k = l; // it sud be initizlized
6+
int B[100];
7+
8+
while (i <= mid && j <= h)
9+
{
10+
if (A[i] < A[j])
11+
B[k++] = A[i++]; // copy element from a to b
12+
else
13+
B[k++] = A[j++]; // copy element from another side of a to b
14+
}
15+
for (; i <= mid; i++)
16+
B[k++] = A[i];
17+
for (; j <= h; j++)
18+
B[k++] = A[j];
19+
20+
for (i = l; i <= h; i++) // this is for copy all the elements from B to A( back )
21+
A[i] = B[i];
22+
}
23+
// recursive fxn for mergesort
24+
void RMergeSort(int A[], int l, int h)
25+
{
26+
int mid;
27+
if (l < h)
28+
{
29+
mid = (l + h) / 2;
30+
RMergeSort(A, l, mid);
31+
RMergeSort(A, mid + 1, h);
32+
Merge(A, l, mid, h); // merging will done in postorder
33+
34+
}
35+
}
36+
int main()
37+
{
38+
int A[] = { 11,13,7,12,16,9,24,5,10,3 }, n = 10, i;
39+
40+
RMergeSort(A,0,n-1); //passing array // low // high
41+
42+
for (i = 0; i < 10; i++)
43+
printf("%d ", A[i]);
44+
printf("\n");
45+
46+
return 0;
47+
}
48+
// TC : O(nlogn) // n is time taken for merging and logn is for the logn time the merging will be performed
49+
// this will take extra space
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
template <class T>
6+
void Print(T& vec, int n, string s){
7+
cout << s << ": [" << flush;
8+
for (int i=0; i<n; i++){
9+
cout << vec[i] << flush;
10+
if (i < n-1){
11+
cout << ", " << flush;
12+
}
13+
}
14+
cout << "]" << endl;
15+
}
16+
17+
void Merge(int A[], int low, int mid, int high){
18+
int i = low;
19+
int j = mid+1;
20+
int k = low;
21+
int B[high+1];
22+
while (i <= mid && j <= high){
23+
if (A[i] < A[j]){
24+
B[k++] = A[i++];
25+
} else {
26+
B[k++] = A[j++];
27+
}
28+
}
29+
while (i <= mid){
30+
B[k++] = A[i++];
31+
}
32+
while (j <= high){
33+
B[k++] = A[j++];
34+
}
35+
for (int i=low; i<=high; i++){
36+
A[i] = B[i];
37+
}
38+
}
39+
40+
void RecursiveMergeSort(int A[], int low, int high){
41+
if (low < high){
42+
// Calculate mid point
43+
int mid = low + (high-low)/2;
44+
45+
// Sort sub-lists
46+
RecursiveMergeSort(A, low, mid);
47+
RecursiveMergeSort(A, mid+1, high);
48+
49+
// Merge sorted sub-lists
50+
Merge(A, low, mid, high);
51+
}
52+
}
53+
54+
int main() {
55+
56+
int A[] = {2, 5, 8, 12, 3, 6, 7, 10};
57+
int n = sizeof(A)/sizeof(A[0]);
58+
59+
Print(A, n, "\t\tA");
60+
RecursiveMergeSort(A, 0, n-1);
61+
Print(A, n, " Sorted A");
62+
63+
return 0;
64+
}

0 commit comments

Comments
 (0)