Skip to content

Commit 5b15ea4

Browse files
committed
add merge sort
1 parent 6da9972 commit 5b15ea4

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

.DS_Store

12 KB
Binary file not shown.

Mersort_In_C++/mergeSort.cpp

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
2+
#include "../helper.h"
3+
#include <iostream>
4+
using namespace std;
5+
6+
void copyArr(int from[], int si, int ei, int * to) {
7+
// while (si <= ei) *to++ = *si++;
8+
while (si <= ei) {
9+
*to = from[si];
10+
++si;
11+
++to;
12+
}
13+
}
14+
15+
16+
void mergeSortedArray(int arr[], int si, int ei, int mid) {
17+
18+
int tmp_A[100];
19+
int tmp_B[100];
20+
21+
copyArr(arr, si, mid, tmp_A);
22+
copyArr(arr, mid + 1, ei, tmp_B);
23+
24+
int i = 0;
25+
int j = 0;
26+
int k = si;
27+
28+
//while a has elements and b has elements, I have to do something
29+
int size_A = mid - si + 1;
30+
int size_B = ei - (mid + 1) + 1;
31+
32+
while (i < size_A && j < size_B) {
33+
if (tmp_A[i] < tmp_B[j]) {
34+
arr[k] = tmp_A[i];
35+
i++;
36+
k++;
37+
}
38+
else {
39+
arr[k++] = tmp_B[j++];
40+
}
41+
}
42+
43+
while (i < size_A) {
44+
arr[k++] = tmp_A[i++];
45+
}
46+
47+
while (j < size_B) arr[k++] = tmp_B[j++];
48+
49+
50+
}
51+
52+
53+
void mergeSort(int arr[], int si, int ei) {
54+
if (si >= ei) {
55+
//no elements
56+
return;
57+
}
58+
59+
int mid = (si + ei) / 2;
60+
//sort the left part
61+
mergeSort(arr, si, mid);
62+
mergeSort(arr, mid + 1, ei);
63+
64+
mergeSortedArray(arr, si, ei, mid);
65+
66+
}
67+
68+
69+
int main() {
70+
int arr[100];
71+
int n;
72+
cin >> n;
73+
inputArr(arr, n);
74+
75+
mergeSort(arr, 0, n - 1);
76+
77+
printArr(arr, n);
78+
}

Mersort_In_C++/mergesort.txt

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Merge Sort is a Divide and Conquer algorithm. It divides input array in
2+
two halves, calls itself for the two halves and then merges the two sorted halves.
3+
Algorithm:
4+
MergeSort(arr[], l, r)
5+
If r > l
6+
1. Find the middle point to divide the array into two halves:
7+
middle m = (l+r)/2
8+
2. Call mergeSort for first half:
9+
Call mergeSort(arr, l, m)
10+
3. Call mergeSort for second half:
11+
Call mergeSort(arr, m+1, r)
12+
4. Merge the two halves sorted in step 2 and 3:
13+
Call merge(arr, l, m, r)

0 commit comments

Comments
 (0)