Skip to content

Instantly share code, notes, and snippets.

@ozkanpakdil
Last active February 4, 2022 16:16
Show Gist options
  • Save ozkanpakdil/5643cf1130dee457e5bff62572abe38c to your computer and use it in GitHub Desktop.
Save ozkanpakdil/5643cf1130dee457e5bff62572abe38c to your computer and use it in GitHub Desktop.
public int[] mergeTwoSortedIntArray(int[] foo, int[] bar) {
int fooLength = foo.length;
int barLength = bar.length;
int[] merged = new int[fooLength + barLength];
int fooPosition, barPosition, mergedPosition;
fooPosition = barPosition = mergedPosition = 0;
while (fooPosition < fooLength && barPosition < barLength) {
if (foo[fooPosition] < bar[barPosition]) {
merged[mergedPosition++] = foo[fooPosition++];
} else {
merged[mergedPosition++] = bar[barPosition++];
}
}
while (fooPosition < fooLength) {
merged[mergedPosition++] = foo[fooPosition++];
}
while (barPosition < barLength) {
merged[mergedPosition++] = bar[barPosition++];
}
return merged;
}
//time complexity O(fooLength + barLength)
//space complexity O(fooLength + barLength)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment