FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java-Programming-Exercises/MergeSort.java at master · RoyTien/Java-Programming-Exercises · GitHub
RoyTien
/
Java-Programming-Exercises
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java-Programming-Exercises
/
MergeSort.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
56 lines (50 loc) · 1.38 KB
Breadcrumbs
Java-Programming-Exercises
/
MergeSort.java
Copy path
File metadata and controls
56 lines (50 loc) · 1.38 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
/*
* Average and worst-case performance of O(n log n).
*/
void
mergesort
(
int
[]
array
,
int
low
,
int
high
){
if
(
low
<
high
){
int
middle
= (
low
+
high
) /
2
;
mergesort
(
array
,
low
,
middle
);
// Sort the left part
mergesort
(
array
,
middle
+
1
,
high
);
// Sort the right part
merge
(
array
,
low
,
middle
,
high
);
// Merge
}
}
void
merge
(
int
[]
array
,
int
low
,
int
middle
,
int
high
){
int
[]
helper
=
new
int
[
array
.
length
];
/*
* Copy the array into helper
*/
for
(
int
i
=
low
;
i
<=
high
;
i
++){
helper
[
i
] =
array
[
i
];
}
int
helperLeft
=
low
;
int
helperRight
=
middle
+
1
;
int
current
=
low
;
/*
* Iterate helper. Compare the elements in left part and
* right part, copy the smaller elements into the
* original array.
*/
while
(
helperLeft
<=
middle
&&
helperRight
<=
high
){
if
(
helper
[
helperLeft
] <=
helper
[
helperRight
]){
array
[
current
] =
helper
[
helperLeft
];
helperLeft
++;
}
else
{
// the right element is smaller than the left one
array
[
current
] =
helper
[
helperRight
];
helperRight
++;
}
current
++;
}
/*
* Copy the rest left elements into target array
* (if these elements are larger than the all right elements)
*/
int
remaining
=
middle
-
helperLeft
;
for
(
int
i
=
0
;
i
<=
remaining
;
i
++){
array
[
current
+
i
] =
helper
[
helperLeft
+
i
]''
}
}
public
static
void
mergesort
(
int
[]
array
){
int
[]
helper
=
new
int
[
array
.
length
];
mergesort
(
array
,
helper
,
0
,
array
.
length
-
1
);
}
Back
|
FazBrowse Home
|
New Git URL