-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_sort.java
More file actions
71 lines (70 loc) · 1.65 KB
/
Merge_sort.java
File metadata and controls
71 lines (70 loc) · 1.65 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
import java.util.Arrays;
import java.util.Scanner;
public class Merge_sort {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter size of array- ");
int n=s.nextInt();
int ar[]=new int[n];
System.out.println("enter array- ");
for (int i = 0; i <n ; i++) {
ar[i]=s.nextInt();
}
mergeSort(ar,0,ar.length-1);
System.out.println("array after sorting is- "+ Arrays.toString(ar));
}
public static void mergeSort(int a[], int beg, int end)
{
int mid;
if(beg<end)
{
mid = (beg+end)/2;
mergeSort(a,beg,mid);
mergeSort(a,mid+1,end);
merge(a,beg,mid,end,a.length);
}
}
public static void merge(int a[], int beg, int mid, int end,int n)
{
int i=beg,j=mid+1,k,index = beg;
int temp[]=new int[n];
while(i<=mid && j<=end)
{
if(a[i]<a[j])
{
temp[index] = a[i];
i = i+1;
}
else
{
temp[index] = a[j];
j = j+1;
}
index++;
}
if(i>mid)
{
while(j<=end)
{
temp[index] = a[j];
index++;
j++;
}
}
else
{
while(i<=mid)
{
temp[index] = a[i];
index++;
i++;
}
}
k = beg;
while(k<index)
{
a[k]=temp[k];
k++;
}
}
}