FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
competitive-programming/Sorting/Merge Sort.cpp at master · kothariji/competitive-programming · GitHub
kothariji
/
competitive-programming
Public
Notifications
You must be signed in to change notification settings
Fork
500
Star
704
Code
Issues
1
Pull requests
2
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
competitive-programming
/
Sorting
/
Merge Sort.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
88 lines (76 loc) · 1.82 KB
Breadcrumbs
competitive-programming
/
Sorting
/
Merge Sort.cpp
Copy path
File metadata and controls
88 lines (76 loc) · 1.82 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#
include
<
iostream
>
using
namespace
std
;
void
merge
(
int
arr[],
int
l,
int
m,
int
r,
int
size)
{
int
i = l;
int
j = m +
1
;
int
k = l;
/*
create temp array
*/
int
temp[size];
while
(i <= m && j <= r) {
if
(arr[i] <= arr[j]) {
temp[k] = arr[i];
i++;
k++;
}
else
{
temp[k] = arr[j];
j++;
k++;
}
}
/*
Copy the remaining elements of first half, if there are any
*/
while
(i <= m) {
temp[k] = arr[i];
i++;
k++;
}
/*
Copy the remaining elements of second half, if there are any
*/
while
(j <= r) {
temp[k] = arr[j];
j++;
k++;
}
/*
Copy the temp array to original array
*/
for
(
int
p = l; p <= r; p++) {
arr[p] = temp[p];
}
}
/*
l is for left index and r is
right index of the
sub-array of arr to be sorted
*/
void
mergeSort
(
int
arr[],
int
l,
int
r,
int
size)
{
if
(l < r) {
//
find midpoint
int
m = (l + r) /
2
;
/*
recurcive mergesort first
and second halves
*/
mergeSort
(arr, l, m, size);
mergeSort
(arr, m +
1
, r, size);
//
merge
merge
(arr, l, m, r, size);
}
}
int
main
()
{
cout <<
"
Enter size of array:
"
<< endl;
int
size;
cin >> size;
int
myarray[size];
cout <<
"
Enter
"
<< size <<
"
integers in any order:
"
<< endl;
for
(
int
i =
0
; i < size; i++) {
cin >> myarray[i];
}
cout <<
"
Before Sorting
"
<< endl;
for
(
int
i =
0
; i < size; i++) {
cout << myarray[i] <<
"
"
;
}
cout << endl;
mergeSort
(myarray,
0
, (size -
1
), size);
//
mergesort(arr,left,right) called
cout <<
"
After Sorting
"
<< endl;
for
(
int
i =
0
; i < size; i++) {
cout << myarray[i] <<
"
"
;
}
return
0
;
}
Back
|
FazBrowse Home
|
New Git URL