-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRecursion-Merge Sort -Problem Statement
68 lines (62 loc) · 1.23 KB
/
Recursion-Merge Sort -Problem Statement
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
Sort an array A using Merge Sort.
Change in the input array itself. So no need to return or print anything.
Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
Sample Input 1 :
6
2 6 8 5 4 3
Sample Output 1 :
2 3 4 5 6 8
Sample Input 2 :
5
2 1 5 2 3
Sample Output 2 :
1 2 2 3 5
****************************Code*******************************
private static void merge(int[] input, int a[], int b[]) {
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i] < b[j]) {
input[k] = a[i];
k++;
i++;
} else {
input[k] = b[j];
k++;
j++;
}
}
while (i < a.length) {
input[k] = a[i];
k++;
i++;
}
while (j < b.length) {
input[k] = b[j];
k++;
j++;
}
}
public static void mergeSort(int[] input){
if (input.length <= 1)
return;
int mid = input.length / 2;
int[] a = new int[mid];
int[] b = new int[input.length - mid];
for (int i = 0; i < mid; i++) {
a[i] = input[i];
}
int k = 0;
for (int i = mid; i < input.length; i++) {
b[k] = input[i];
k++;
}
mergeSort(a);
mergeSort(b);
merge(input, a, b);
}