-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.java
50 lines (44 loc) · 1.21 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
import java.util.Arrays;
/**
*
* @author ABDULLA
*/
public class MergeSort {
public static int[] mergeSort(int a[])
{
if(a.length==1)
return a;
int mid=a.length/2;
int left[]= mergeSort(Arrays.copyOfRange(a,0,mid));
int right[]=mergeSort(Arrays.copyOfRange(a, mid,a.length));
return merge(left,right);
}
public static int[] merge(int[] l,int[] r)
{
int merge[]=new int[l.length+r.length];
int i=0,j=0,k=0;
while(i<l.length && j<r.length)
{
if(l[i]<r[j])
merge[k++]=l[i++];
else
merge[k++]=r[j++];
}
while(i<l.length)
{
merge[k++]=l[i++];
}
while(j<r.length)
{
merge[k++]=r[j++];
}
return merge;
}
public static void main(String[] args) {
int arr[]={76,34,67,23,65,90,45};
System.out.println("Before Sorting ");
System.out.println(Arrays.toString(arr));
System.out.println("After Sorting ");
System.out.println(Arrays.toString(mergeSort(arr)));
}
}