forked from joney000/Java-Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
executable file
·58 lines (45 loc) · 1.53 KB
/
MergeSort.java
File metadata and controls
executable file
·58 lines (45 loc) · 1.53 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
/* package joney_000 */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
class Main
{
public static void main(String[] args)throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out=new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int arr [] = new int[100005];
String[] s = br.readLine().split(" ");
for(int i=1;i<=n;i++)arr[i]=Integer.parseInt(s[i-1]);
mergeSort(arr,1,n);
for(int i=1;i<=n;i++)out.write(""+arr[i]+" ");
out.flush();
}
public static void mergeSort(int arr[],int st ,int end)throws Exception{
if(st>=end)return;
int mid = (st+end)/2; ////Same as mid=l+(r-l)/2;, but this avoids integer overflow for large l and h
mergeSort(arr,st,mid);
mergeSort(arr,mid+1,end);
merge(arr,st,mid,end);
}
public static void merge(int arr[],int st ,int mid, int end)throws Exception{
LinkedList<Integer> L = new LinkedList<Integer>();
LinkedList<Integer> R = new LinkedList<Integer>();
for(int i=st;i<=mid;i++)L.add(arr[i]);
for(int i=mid+1;i<=end;i++)R.add(arr[i]);
while((!L.isEmpty())&&(!R.isEmpty())){
int a = L.getFirst();
int b = R.getFirst();
if(a<=b){
arr[st]=L.removeFirst();
st++;
}else{
arr[st]=R.removeFirst();
st++;
}
}
while(!L.isEmpty()){arr[st]=L.removeFirst();st++;}
while(!R.isEmpty()){arr[st]=R.removeFirst();st++;}
}
}