-
Notifications
You must be signed in to change notification settings - Fork 22
/
FindMedianBetween2SortedArraysOfUnequalLength
315 lines (268 loc) · 10.7 KB
/
FindMedianBetween2SortedArraysOfUnequalLength
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
*********** Using Logic of "finding kth smallest element between two sorted arrays of unequal length"***************
/*
Question: http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
Source: http://algorithmsandme.blogspot.com/2014/12/find-median-of-two-sorted-arrays-of.html#.VLNiR5_0_VN
http://algorithmsandme.blogspot.in/2014/12/fins-kth-smallest-element-in-two-sorted.html#.VLNiz5_0_VN
http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
*/
package FindMedianBetween2SortedArraysOfUnequalLength;
import java.util.Arrays;
import java.util.Scanner;
public class UsingKthSmallestElementLogic {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the number of elements in the first SORTED array");
int n = in.nextInt();
int[] array1 = new int[n];
System.out.println("Enter the elements of the first SORTED array");
for(int i=0;i<n;i++)
array1[i]=in.nextInt();
System.out.println("Enter the number of elements in the second SORTED array");
int m = in.nextInt();
int[] array2 = new int[m];
System.out.println("Enter the elements of the second SORTED array");
for(int i=0;i<m;i++)
array2[i]=in.nextInt();
System.out.println("Median of the two SORTED arrays is: "+findMedian(array1,array2,array1.length,array2.length));
}
finally{
in.close();
}
}
private static int findMedian(int[] a, int[] b,
int aLength, int bLength) {
int left = (aLength+bLength+1)>>1;
int right = (aLength+bLength+2)>>1;
return ((findKthSmallestElement(a,b,a.length,b.length,left)+findKthSmallestElement(a,b,a.length,b.length,right))/2);
}
private static int findKthSmallestElement(int[] a, int[] b,
int aLength, int bLength, int k) { // All the 5 parameters passed are VERY VERY IMP
/* to maintain uniformity, we will assume that size_a is smaller than size_b
else we will swap array in call :) */
if(aLength>bLength)
return findKthSmallestElement(b, a, bLength, aLength, k);
/* We have TWO BASE CASES
* Now case when size of smaller array is 0 i.e there is no elemt in one array*/
//BASE CASE 1. If the smallest array length is 0
if(aLength == 0 && bLength > 0)
return b[k-1]; // due to zero based index
/* case where k==1 that means we have hit limit */
//BASE CASE 2. If k==1
if(k==1)
return Math.min(a[0], b[0]);
/* Now the divide and conquer part */
int i = Math.min(aLength, k/2) ; // k should be less than the size of array
int j = Math.min(bLength, k/2) ; // k should be less than the size of array
if(a[i-1] > b[j-1])
// Now we need to find only K-j th element
return findKthSmallestElement(a, Arrays.copyOfRange(b, j, b.length), a.length, b.length -j, k-j);
else
return findKthSmallestElement(Arrays.copyOfRange(a, i, a.length), b, a.length-i, b.length, k-i);
}
}
/*
Analysis:
Time Complexity = O(log(n+m))
Space Complexity = O(1)*/
**************************** Using comparison of individual medians *************************************
/*
Question: Median of two sorted arrays of different sizes
Source: http://www.geeksforgeeks.org/median-of-two-sorted-arrays-of-different-sizes/
http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
*/
package FindMedianBetween2SortedArraysOfUnequalLength;
import java.util.Arrays;
import java.util.Scanner;
public class ComparingIndividualMedians {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the number of elements in the first SORTED array");
int n = in.nextInt();
int[] array1 = new int[n];
System.out.println("Enter the elements of the first SORTED array");
for(int i=0;i<n;i++)
array1[i]=in.nextInt();
System.out.println("Enter the number of elements in the second SORTED array");
int m = in.nextInt();
int[] array2 = new int[m];
System.out.println("Enter the elements of the second SORTED array");
for(int i=0;i<m;i++)
array2[i]=in.nextInt();
System.out.println("Median of the two SORTED arrays is: "+findMedian(array1,array2,array1.length,array2.length));
}
finally{
in.close();
}
}
private static int findMedian(int[] a, int[] b, int aLength,int bLength) {
if(aLength>bLength)
return findMedianUtil(b,a,bLength,aLength);
else
return findMedianUtil(a,b,aLength,bLength);
}
private static int findMedianUtil(int[] A, int[] B, int N, int M) {
// If the smaller array has only one element
if( N == 1 )
{
// Case 1: If the larger array also has one element, simply call MO2()
if( M == 1 )
return MO2( A[0], B[0] );
// Case 2: If the larger array has odd number of elements, then consider
// the middle 3 elements of larger array and the only element of
// smaller array. Take few examples like following
// A = {9}, B[] = {5, 8, 10, 20, 30} and
// A[] = {1}, B[] = {5, 8, 10, 20, 30}
if( (M & 1)!=0 )
return MO2( B[M/2], MO3(A[0], B[M/2 - 1], B[M/2 + 1]) );
// Case 3: If the larger array has even number of element, then median
// will be one of the following 3 elements
// ... The middle two elements of larger array
// ... The only element of smaller array
return MO3( B[M/2], B[M/2 - 1], A[0] );
}
// If the smaller array has two elements
else if( N == 2 )
{
// Case 4: If the larger array also has two elements, simply call MO4()
if( M == 2 )
return MO4( A[0], A[1], B[0], B[1] );
// Case 5: If the larger array has odd number of elements, then median
// will be one of the following 3 elements
// 1. Middle element of larger array
// 2. Max of first element of smaller array and element just
// before the middle in bigger array
// 3. Min of second element of smaller array and element just
// after the middle in bigger array
if( (M & 1) !=0)
return MO3 ( B[M/2],
max( A[0], B[M/2 - 1] ),
min( A[1], B[M/2 + 1] )
);
// Case 6: If the larger array has even number of elements, then
// median will be one of the following 4 elements
// 1) & 2) The middle two elements of larger array
// 3) Max of first element of smaller array and element
// just before the first middle element in bigger array
// 4. Min of second element of smaller array and element
// just after the second middle in bigger array
return MO4 ( B[M/2],
B[M/2 - 1],
max( A[0], B[M/2 - 2] ),
min( A[1], B[M/2 + 1] )
);
}
int idxA = ( N - 1 ) / 2;
int idxB = ( M - 1 ) / 2;
/* if A[idxA] <= B[idxB], then median must exist in
A[idxA....] and B[....idxB] */
if( A[idxA] <= B[idxB] )
return findMedianUtil( Arrays.copyOfRange(A, idxA, A.length), B, N / 2 + 1, M - idxA );
/* if A[idxA] > B[idxB], then median must exist in
A[...idxA] and B[idxB....] */
return findMedianUtil( A, Arrays.copyOfRange(B, idxA, A.length), N / 2 + 1, M - idxA );
}
//A utility function to find maximum of two integers
public static int max( int a, int b )
{ return a > b ? a : b; }
//A utility function to find minimum of two integers
public static int min( int a, int b )
{ return a < b ? a : b; }
//A utility function to find median of two integers
public static int MO2( int a, int b )
{ return ( a + b ) / 2; }
//A utility function to find median of three integers
public static int MO3( int a, int b, int c )
{
return a + b + c - max( a, max( b, c ) )
- min( a, min( b, c ) );
}
//A utility function to find median of four integers
public static int MO4( int a, int b, int c, int d )
{
int Max = max( a, max( b, max( c, d ) ) );
int Min = min( a, min( b, min( c, d ) ) );
return ( a + b + c + d - Max - Min ) / 2;
}
}
/*
Analysis:
Time Complexity = O(lgN+lgM)
Space Complexity = O(1)
*/
**************************** Using Merge method of Mergesort ********************************************
/*
Question: http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
Source: http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
http://theoryapp.com/find-median-of-two-sorted-arrays/
*/
package FindMedianBetween2SortedArraysOfUnequalLength;
import java.util.Scanner;
public class UsingMergeMethodOfMergeSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try{
System.out.println("Enter the number of elements in the first SORTED array");
int n = in.nextInt();
int[] array1 = new int[n];
System.out.println("Enter the elements of the first SORTED array");
for(int i=0;i<n;i++)
array1[i]=in.nextInt();
System.out.println("Enter the number of elements in the second SORTED array");
int m = in.nextInt();
int[] array2 = new int[m];
System.out.println("Enter the elements of the second SORTED array");
for(int i=0;i<m;i++)
array2[i]=in.nextInt();
System.out.println("Median of the two SORTED arrays is: "+findMedianUsingMergeOfMergeSort(array1,array2));
}
finally{
in.close();
}
}
private static int findMedianUsingMergeOfMergeSort(int[] a, int[] b) {
/* a1 array and a2 array can be of different lengths.
For Example:
1.
a1.length = 3
a2.length = 6
totalElements = 3+6=9 (odd number)
2.
a1.length = 4
a2.length = 4
totalElements = 4+4=8 (even number)
*/
int totalElements = a.length+b.length; // totalElements is the addition of the individual array lengths
int currentMedian = 0;
int prevMedian = 0;
int i=0; // Index for traversing array1
int j=0; // Index for traversing array2
for(int k=0;k<totalElements;k++){ // k is index for traversing the totalElements of array1 and array2
/*NOTE: In this entire for loop, the "if", "else" and "else if" is VERY IMP. DONOT interchange among them*/
// if array1 is exhausted
if(i==a.length)
currentMedian=b[j++]; // elements of the second array would be considered
// if array2 is exhausted
else if(j==b.length)
currentMedian=a[i++]; // elements of the first array would be considered
else if(a[i]<b[j])
currentMedian=a[i++];
else //(b[j]<=a[i]) // this condition is ONLY "else" and not "if" OR "else if"
currentMedian=b[j++];
if(k==totalElements/2) // we reached the middle of the totalElements where the median of the combined arrays is found
break;
prevMedian = currentMedian;
}
// if the totalElements are odd
if(totalElements%2!=0)
return currentMedian;
else
return (prevMedian+currentMedian)/2;
}
}
/*
Analysis:
Time Complexity = Linear Time, O((m+n)/2)
Space Complexity = O(1)
*/