-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathMergeSort.java
64 lines (50 loc) · 1.41 KB
/
MergeSort.java
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
import java.util.Arrays;
import java.util.Scanner;
public class MergeSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Length:- ");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println(Arrays.toString(mergesort(arr)));
}
private static int[] mergesort(int[] arr) {
if (arr.length == 1)
return arr;
int m = arr.length / 2;
int[] left = mergesort(Arrays.copyOfRange(arr, 0, m));
int[] right = mergesort(Arrays.copyOfRange(arr, m, arr.length));
return merge(left, right);
}
private static int[] merge(int[] l, int[] r) {
int[] ans = new int[l.length + r.length];
int index = 0;
int i = 0;
int j = 0;
while (i < l.length && j < r.length) {
if (l[i] < r[j]) {
ans[index] = l[i];
i++;
index++;
} else {
ans[index] = r[j];
j++;
index++;
}
}
while (i < l.length) {
ans[index] = l[i];
i++;
index++;
}
while (j < r.length) {
ans[index] = r[j];
j++;
index++;
}
return ans;
}
}