-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
56 lines (45 loc) · 1.2 KB
/
MergeSort.java
File metadata and controls
56 lines (45 loc) · 1.2 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
import java.util.Arrays;
public class MergeSort{
static public int[] mergesort(int arr[]){
if(arr.length == 1){
return arr;
}
int mid = arr.length/2;
int left[] = mergesort(Arrays.copyOfRange(arr, 0, mid));
int right[] = mergesort(Arrays.copyOfRange(arr, mid, arr.length));
return merge(left,right);
}
static public int[] merge(int first[],int second[]){
int i=0;
int j=0;
int k=0;
int mix[] = new int[first.length+second.length];
while(i<first.length && j<second.length){
if(first[i]<second[j]){
mix[k] = first[i];
i++;
}
else{
mix[k] = second[j];
j++;
}
k++;
}
while(i<first.length){
mix[k] = first[i];
i++;
k++;
}
while(j<second.length){
mix[k] = second[j];
j++;
k++;
}
return mix;
}
public static void main(String args[]){
int arr[] = {3,6,5,7,8};
arr = MergeSort.mergesort(arr);
System.out.println(Arrays.toString(arr));
}
}