Last active
June 3, 2020 21:03
-
-
Save lion4ik/472846a292e9271f95da345510f99822 to your computer and use it in GitHub Desktop.
Merge sorted arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test | |
import java.util.* | |
class MergeArraySortTest { | |
@Test | |
fun test() { | |
val original = LinkedList(mutableListOf(4, 5, 8, 11, 15, 17, 20)) //n | |
val addition = | |
LinkedList(mutableListOf(1, 3, 6, 10, 11, 13, 19, 21)) //m | |
println(mergeSortedArrays(original, addition)) | |
} | |
private fun mergeSortedArrays(original: LinkedList<Int>, addition: LinkedList<Int>): List<Int> { | |
if (original.isEmpty()) { | |
return addition | |
} | |
var j = 0 | |
for (i in 0 until addition.size) { | |
when { | |
addition[i] <= original.first() -> original.add(i, addition[i]) | |
addition[i] > original.last() -> original.add(addition[i]) | |
else -> { | |
for (k in j until original.size) { | |
if (addition[i] <= original[k]) { | |
original.add(k, addition[i]) | |
j = k | |
break | |
} | |
} | |
} | |
} | |
} | |
return original | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment