forked from AdityaSubrahmanyaBhat/hacktoberfest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.java
55 lines (51 loc) · 1.23 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 com.company;
import java.util.Arrays;
public class mergeSort {
public static void main(String[] args) {
int[] arr = {3,2,1,4,5,7,6,9,8,11,10,14,12,13};
int[] ans=sort(arr);
System.out.println(Arrays.toString(ans));
}
static int[] sort(int[] arr)
{
if(arr.length==1)
{
return arr;
}
int[] left=sort(Arrays.copyOfRange(arr,0,arr.length/2));
int[] right=sort(Arrays.copyOfRange(arr,arr.length/2,arr.length));
return merge(left,right);
}
static int[] merge(int[] first,int[] second)
{
int[] mix=new int[first.length+second.length];
int i=0,j=0,k=0;
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;
}
}