forked from Arunvijay28/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.java
95 lines (79 loc) · 1.89 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.util.Scanner;
class Merge1
{
public static void merge(int arr[], int left, int right, int mid)
{
int n1=mid-left+1;
int n2=right-mid;
int[] L=new int[n1];
int[] R=new int[n2];
for(int i=0;i<L.length;i++)
{
L[i]=arr[left+i];
}
for(int j=0;j<R.length;j++)
{
R[j]=arr[mid+1+j];
}
int i=0;
int j=0;
int k=left;
while(i<n1 && j<n2)
{
if(L[i]<=R[j])
{
arr[k]=L[i];
i++;
}
else
{
arr[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
arr[k]=L[i];
i++;
k++;
}
while(j<n2)
{
arr[k]=R[j];
j++;
k++;
}
}
public static void mergesort(int arr[],int left,int right)
{
if(left<right)
{
int mid=(left+right)/2;
mergesort(arr,left,mid);
mergesort(arr,mid+1,right);
merge(arr,left,right,mid);
}
}
}
public class MergeSort
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array:");
int size=sc.nextInt();
int[] arr=new int[size];
System.out.println("Enter the elements of array:");
for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
Merge1.mergesort(arr,0,arr.length-1);
System.out.println("Sorted Array is:");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}