-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.java
55 lines (53 loc) · 1.06 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
package Module1;
import java.util.*;
public class MergeSort {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
merge_sort(a, 0 , n-1);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
sc.close();
}
static void merge_sort(int a[], int low, int high) {
if(low<high) {
int mid = (low+high)/2;
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
static void merge(int a[], int low, int mid, int high) {
int i=low, j=mid+1, k=low, pos;
int temp[] = new int[a.length];
while(i<=mid && j<=high) {
if(a[i] < a[j]) {
temp[k] = a[i];
i++;
}
else {
temp[k] = a[j];
j++;
}
k++;
}
if(i > mid) {
for(pos=j;pos<=high;pos++) {
temp[k] = a[pos];
k++;
}
}
else {
for(pos=i;pos<=mid;pos++) {
temp[k] = a[pos];
k++;
}
}
for(pos=low;pos<=high;pos++) {
a[pos] = temp[pos];
}
}
}