-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
62 lines (52 loc) · 1.57 KB
/
MergeSort.java
File metadata and controls
62 lines (52 loc) · 1.57 KB
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
import java.util.Arrays;
public class MergeSort {
public int[] sortArray(int[] A) {
if (A == null) {
System.out.println("Array is epmty!");
return null;
}
if (A.length < 2) {
return A;
}
int[] B = new int[A.length / 2];
System.arraycopy(A, 0, B, 0, A.length / 2);
int[] C = new int[A.length - A.length / 2];
System.arraycopy(A, A.length / 2, C, 0, A.length - A.length / 2);
B = sortArray(B);
C = sortArray(C);
return mergeArray(B, C);
}
public int[] mergeArray(int[] B, int[] C) {
int[] A = new int[B.length + C.length];
int posB = 0, posC = 0;
for (int i = 0; i < A.length; i++) {
if (posB == B.length) {
A[i] = C[posC];
posC++;
} else if (posC == C.length) {
A[i] = B[posB];
posB++;
} else if (B[posB] < C[posC]) {
A[i] = B[posB];
posB++;
} else {
A[i] = C[posC];
posC++;
}
}
return A;
}
public int[] fillArray() {
int[] A = new int[6];
for (int i = 0; i < A.length; i++) {
A[i] = (int) (Math.random() * 10) + 1;
}
return A;
}
public static void main(String[] args) {
MergeSort a = new MergeSort();
int[] Array = a.fillArray();
System.out.println(Arrays.toString(Array));
System.out.println(Arrays.toString(a.sortArray(Array)));
}
}