forked from Dipak3007/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
86 lines (73 loc) · 2.35 KB
/
MergeSort.java
File metadata and controls
86 lines (73 loc) · 2.35 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.*;
public class MergeSort {
//method to print the elements of the array
static void mergedArray(int arr[])
{
StringBuffer sb=new StringBuffer("");
int n = arr.length;
for (int i=0; i<n; ++i)
sb.append(arr[i]+" ");
System.out.println(sb.toString());
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
//checking all ans for various testcases
int ans = sc.nextInt();
while(ans>0)
{
int n = sc.nextInt();
MergeSort ms = new MergeSort();
//array created for storing elements
int arr[] = new int[n];
//adding elements to the array
for(int i=0;i<n;i++)
arr[i] = sc.nextInt();
Merge me = new Merge();
//calling the method mergeSort
me.mergeSort(arr,0,arr.length-1);
//calling the method printArray
ms.mergedArray(arr);
ans--;
}
}
}
// } Driver Code Ends
class Merge
{
void merge(int arr[], int left, int mid, int right)
{
int[] merged = new int[right-left+1];
int ind1=left;
int ind2=mid+1;
int x=0;
while(ind1<=mid&&ind2<=right){
if(arr[ind1]<arr[ind2]){
merged[x++] = arr[ind1++] ;
}else{
merged[x++] =arr[ind2++] ;
}
}
while(ind1<=mid){
merged[x++]= arr[ind1++] ;
}
while(ind2<=right){
merged[x++] =arr[ind2++] ;
}
for(int i=0,j=left;i<merged.length;i++,j++){
arr[j] = merged[i];
}
}
void mergeSort(int arr[], int l, int r)
{
// return merged arr;
if(l>=r){
return ;
}
int mid = l+(r-l)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,mid,r);
}
}