-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Sort.java
More file actions
73 lines (48 loc) · 1.41 KB
/
Merge_Sort.java
File metadata and controls
73 lines (48 loc) · 1.41 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Arrays;
public class Merge_Sort{
static 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 int[] merge(int[] first, int[] second){
int[] mix = new int[first.length + second.length];
int i = 0;
int j = 0;
int k = 0;
// Comparing elements of the two arrays, less one is assigned to mix[]
while(i<first.length && j<second.length ){
if(first[i] < second[j]){
mix[k] = first[i];
i++;
k++;
}
else{
mix[k] = second[j];
j++;
k++;
}
}
// If one array elements are more than the other one, assign rest of array to mix[]
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 = {8,4,3,12,5,6};
arr=mergeSort(arr);
System.out.println("After Merge sort : "+Arrays.toString(arr));
}
}