How to merge sorted arrays: Renamed the variables

This commit is contained in:
Vivek Balasubramaniam 2019-11-30 18:20:38 +05:30
parent 2f020d30ba
commit 277a1ee266

View File

@ -4,29 +4,29 @@ public class SortedArrays {
public static int[] merge(int[] first, int[] second) { public static int[] merge(int[] first, int[] second) {
int m = first.length; int firstLength = first.length;
int n = second.length; int secondLength = second.length;
int i, j, k; int[] result = new int[firstLength + secondLength];
i = j = k = 0;
int[] result = new int[m + n]; int firstPosition, secondPosition, resultPosition;
firstPosition = secondPosition = resultPosition = 0;
while (i < m && j < n) { while (firstPosition < firstLength && secondPosition < secondLength) {
if (first[i] < second[j]) { if (first[firstPosition] < second[secondPosition]) {
result[k++] = first[i++]; result[resultPosition++] = first[firstPosition++];
} else { } else {
result[k++] = second[j++]; result[resultPosition++] = second[secondPosition++];
} }
} }
while (i < m) { while (firstPosition < firstLength) {
result[k++] = first[i++]; result[resultPosition++] = first[firstPosition++];
} }
while (j < n) { while (secondPosition < secondLength) {
result[k++] = second[j++]; result[resultPosition++] = second[secondPosition++];
} }
return result; return result;