Skip to content

Instantly share code, notes, and snippets.

@courtneyfaulkner
Created September 6, 2017 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save courtneyfaulkner/72b62bdae4b4a9399026077535568bc4 to your computer and use it in GitHub Desktop.
Save courtneyfaulkner/72b62bdae4b4a9399026077535568bc4 to your computer and use it in GitHub Desktop.
[SortedArrays] #practice
class SortedArrays {
/*
For Example
A = {10, 15, 25}
B = {1, 5, 20, 30}
The resulting arrays are:
10 20
10 20 25 30
10 30
15 20
15 20 25 30
15 30
25 30
*/
static void main(String[] args) {
println mergeSort([10, 15, 25] as int[], [1, 5, 20, 30] as int[])
}
static List<List<Integer>> mergeSort(int[] arrA, int[] arrB) {
List<List<Integer>> results = new ArrayList<List<Integer>>()
Integer baseA = 0, latestA = 0, priorBaseA = 0
Integer baseB = 0, latestB = 0
List<Integer> chain = new ArrayList<Integer>()
while (true) {
Integer arrAValue = arrA.find {it > baseA && it > latestA && it > latestB}
if (arrAValue) {
if (latestA == 0) {
priorBaseA = baseA
baseA = arrAValue
}
latestA = arrAValue
chain.add(arrAValue)
Integer arrBValue = arrB.find {it > arrAValue && it > baseB}
if (arrBValue) {
if (baseA == arrAValue) baseB = arrBValue
latestB = arrBValue
chain.add(arrBValue)
results.add(chain)
chain = chain.clone()
} else {
latestA = 0
latestB = 0
baseB = 0
chain = new ArrayList<Integer>()
}
} else {
if (baseA == arrA[arrA.length - 1]) {
break
} else {
baseA = priorBaseA
latestA = 0
latestB = 0
chain = new ArrayList<Integer>()
}
}
}
results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment