-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedArrays.java
More file actions
109 lines (100 loc) · 2.54 KB
/
MergeSortedArrays.java
File metadata and controls
109 lines (100 loc) · 2.54 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package algorithm.sorting.problems;
import java.util.Arrays;
/**
* The type Merge sorted arrays.
*/
public class MergeSortedArrays {
/**
* Median float.
*
* @param arr1 the arr 1
* @param arr2 the arr 2
* @return the float
*/
public static float median(int[] arr1, int[] arr2) {
int[] array = merge(arr1, arr2);
int l = array.length;
if (l % 2 == 0) {
float num = ((array[l / 2 - 1] + array[l / 2]));
return num / 2;
} else {
return array[l / 2];
}
}
/**
* Merge int [ ].
*
* @param arr1 the arr 1
* @param arr2 the arr 2
* @return the int [ ]
*/
public static int[] merge(int[] arr1, int[] arr2) {
int l1 = arr1.length;
int l2 = arr2.length;
int[] array = new int[l1 + l2];
int i = 0, j = 0, k = 0;
while (i < l1 && j < l2) {
if (arr1[i] < arr2[j]) {
array[k++] = arr1[i++];
} else if (arr1[i] == arr2[j]) {
array[k++] = arr1[i++];
array[k++] = arr2[j++];
} else {
array[k++] = arr2[j++];
}
}
while (j < l2) {
array[k++] = arr2[j++];
}
while (i < l1) {
array[k++] = arr1[i++];
}
return array;
}
/**
* Get median using partition array float.
*
* @param arr1 the arr 1
* @param arr2 the arr 2
* @return the float
*/
public static float getMedianUsingPartitionArray(int[] arr1, int[] arr2){
return 0.0F;
}
/**
* The entry point of application.
*
* @param args the input arguments
*/
public static void main(String[] args) {
int array1[] = {
4,
5,
7,
10
};
int array2[] = {
12,
13,
15,
18,
20,
24
};
System.out.println("The median of " + Arrays.toString(array1) + " and " + Arrays.toString(array2) + " is " + median(array1, array2));
int array3[] = {
1,
2,
3,
4,
5
};
int array4[] = {
100,
200,
300,
400
};
System.out.println("The median of " + Arrays.toString(array3) + " and " + Arrays.toString(array4) + " is " + median(array3, array4));
}
}