-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge sort
78 lines (63 loc) · 1.63 KB
/
Merge sort
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
68
69
70
71
72
73
74
75
76
77
78
//Merge sort
import java.util.*;
class Merge_Sort {
static void printArray(int arr[]) {
StringBuffer sb=new StringBuffer("");
int n = arr.length;
for(int i = 0; i < n; ++i)
sb.append(arr[i] + " ");
System.out.println(sb.toString());
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T > 0) {
int n = sc.nextInt();
Merge_Sort ms = new Merge_Sort();
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
Solution g = new Solution();
g.mergeSort(arr, 0, arr.length - 1);
ms.printArray(arr);
T--;
}
}
}
class Solution {
void merge(int arr[], int l, int m, int r) {
ArrayList<Integer> temp = new ArrayList<>();
int left = l;
int right = m + 1;
while(left <= m && right <= r) {
if(arr[left] <= arr[right]) {
temp.add(arr[left]);
left++;
}
else {
temp.add(arr[right]);
right++;
}
}
while(left <= m) {
temp.add(arr[left]);
left++;
}
while(right <= r) {
temp.add(arr[right]);
right++;
}
for(int i = l; i <= r; i++) {
arr[i] = temp.get(i - l);
}
}
void mergeSort(int arr[], int l, int r) {
if(l >= r) {
return;
}
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}