-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.java
135 lines (67 loc) · 2.11 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class MergeSort {
// Function to merge the two sorted arrays
static void merge(int[] array,int low,int mid,int high){
int i,j,k;
int[] c= new int[high-low+1];
k = 0;
i=low;
j=mid+1;
while(i<=mid && j<=high){
if(array[i]<=array[j]){
c[k++] = array[i++];
}
else{
c[k++] = array[j++];
}
}
while(i<=mid){
c[k++] = array[i++];
}
while(j<=high){
c[k++] = array[j++];
}
k=0;
for(i = low; i<=high; i++){
array[i] = c[k++];
}
}
// Function implementing the merge sort
static void mergeSort(int[] array,int low, int high){
if(high-low+1>1){
int mid = (low+high)/2;
mergeSort(array,low,mid);
mergeSort(array,mid+1,high);
merge(array,low,mid,high);
}
}
// Function to read the input and display the output
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error Occurred");
}
}
System.out.println("The initial array is");
System.out.println(Arrays.toString(array));
mergeSort(array,0,array.length-1);
System.out.println("The sorted array is");
System.out.println(Arrays.toString(array));
}
}