Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit dde7a46

Browse files
add MergeSort.java
1 parent 22c25a1 commit dde7a46

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

‎src/MergeSort.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
public class MergeSort {
2+
3+
public static int[] mergeTwoSortedArrays(int[] one, int[] two) {
4+
5+
int[] sorted = new int[one.length + two.length];
6+
7+
int i = 0;
8+
int j = 0;
9+
int k = 0;
10+
11+
while (i < one.length && j < two.length) {
12+
13+
if (one[i] < two[j]) {
14+
sorted[k] = one[i];
15+
k++;
16+
i++;
17+
} else {
18+
sorted[k] = two[j];
19+
k++;
20+
j++;
21+
}
22+
}
23+
24+
if (i == one.length) {
25+
26+
while (j < two.length) {
27+
sorted[k] = two[j];
28+
k++;
29+
j++;
30+
}
31+
}
32+
33+
if (j == two.length) {
34+
35+
while (i < one.length) {
36+
sorted[k] = one[i];
37+
k++;
38+
i++;
39+
}
40+
}
41+
42+
return sorted;
43+
44+
}
45+
46+
public static int[] mergeSort(int[] arr, int lo, int hi) {
47+
48+
if (lo == hi) {
49+
int[] br = new int[1];
50+
br[0] = arr[lo];
51+
52+
return br;
53+
}
54+
55+
int mid = (lo + hi) / 2;
56+
57+
int[] fh = mergeSort(arr, lo, mid);
58+
int[] sh = mergeSort(arr, mid + 1, hi);
59+
60+
int[] merged = mergeTwoSortedArrays(fh, sh);
61+
62+
return merged;
63+
}
64+
65+
public static void main(String[] args) {
66+
67+
int[] arr = { 70, 50, 30, 10, 20, 40, 60 };
68+
69+
int[] merged = mergeSort(arr, 0, arr.length - 1);
70+
71+
for (int val : merged) {
72+
System.out.print(val + " ");
73+
}
74+
75+
}
76+
77+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /