forked from Fabayu/HACKTOBERFEST-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge_sort.cpp
93 lines (74 loc) · 1.81 KB
/
Merge_sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
using namespace std;
void merge(int *arr, int start, int end);
void merge_sort(int *arr, int start, int end)
{
// base case
if (start >= end)
return;
int mid = start + (end - start) / 2;
// left part sort
merge_sort(arr, start, mid);
// right part sort
merge_sort(arr, mid + 1, end);
// for merging two sorted arrays
merge(arr, start, end);
}
void merge(int *arr, int start, int end)
{
int mid = start + (end - start) / 2;
// length of both array
int len1 = mid - start + 1;
int len2 = end - mid;
// create new dynamic array
int *first = new int[len1];
int *second = new int[len2];
// copy first array in *first
int mainArrayIndex = start;
for (int i = 0; i < len1; i++)
{
first[i] = arr[mainArrayIndex++];
}
// copy second array in *second
mainArrayIndex = mid + 1;
for (int i = 0; i < len2; i++)
{
second[i] = arr[mainArrayIndex++];
}
// merge 2 sorted array
int index1 = 0;
int index2 = 0;
mainArrayIndex = start;
// dono index ko compare kar ra , jo chota hai usko arr mai daal ra .
while (index1 < len1 && index2 < len2)
{
if (first[index1] < second[index2])
{
arr[mainArrayIndex++] = first[index1++];
}
if (first[index1] > second[index2])
{
arr[mainArrayIndex++] = second[index2++];
}
}
// agar index 1 ke element bach gaye ho to .
while (index1 < len1)
{
arr[mainArrayIndex++] = first[index1++];
}
// agar index 2 ke element bach gaye ho to .
while (index1 < len2)
{
arr[mainArrayIndex++] = second[index2++];
}
}
int main()
{
int arr[5] = {82, 924, 91, 5, 29};
int n = 5;
merge_sort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}