-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathmerge-sort.java
66 lines (64 loc) · 1.39 KB
/
merge-sort.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
56
57
58
59
60
61
62
63
64
65
66
// Java program to perform Merge Sort algorithm on a array
public class MergeSort
{
static void mergeSort(int arr[],int l,int r)
{
if(r>l)
{
int mid = l+(r-l)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}
static void merge(int arr[],int l,int m,int r)
{
int l1 = m+1-l;
int l2 = r-m;
int[] arr1 = new int[l1];
int[] arr2 = new int[l2];
int i = 0,j = 0;
for(int f=0;f<l1;f++)
{
arr1[f] = arr[l+f];
}
for(int f=0;f<l2;f++)
{
arr2[f] = arr[m+1+f];
}
int k = l;
while(i<l1 && j<l2)
{
if(arr1[i]<arr2[j])
{
arr[k] = arr1[i];
k++;
i++;
}
else
{
arr[k] = arr2[j];
k++;
j++;
}
}
while(i<l1)
{
arr[k] = arr1[i];
i++;
k++;
}
while(j<l2)
{
arr[k] = arr2[j];
j++;
k++;
}
}
public static void main(String[] args) {
int arr[] = {10,9,8,7,6,5,4,3,2,1};
mergeSort(arr,0,arr.length-1);
for(int num: arr)
System.out.print(num + " ");
}
}