Created
September 12, 2017 02:58
-
-
Save nathaniel-miller/829cc71e65ed8834476a039f25953765 to your computer and use it in GitHub Desktop.
Lifion Array Intersection
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
function intersection(a, b) { | |
a = quickSort(a); | |
b = quickSort(b); | |
let results = []; | |
for(let i = 0; i < a.length; i++) { | |
let current = a[i]; | |
let triedThis; | |
if(current == a[i - 1]) { | |
triedThis = true; | |
} else { | |
triedThis = false; | |
} | |
if(triedThis == false) { | |
let hi = b.length; | |
while(hi >= 0) { | |
let mid = Math.floor(hi / 2); | |
if(b[mid] == current) { | |
results.push(current); | |
b = b.slice(mid + 1); | |
break; | |
} else if(b[mid] < current) { | |
b = b.slice(mid + 1); | |
} else { | |
hi = mid - 1; | |
} | |
} | |
} | |
} | |
return results; | |
} | |
function quickSort(array) { | |
if(array.length < 2) { | |
return array; | |
} | |
let pivot = array[0]; | |
let l = []; | |
let g = []; | |
for(let i = 1; i < array.length; i++) { | |
array[i] < pivot ? l.push(array[i]) : g.push(array[i]); | |
} | |
return quickSort(l).concat(pivot, quickSort(g)); | |
} | |
console.log(intersection([1, 2, 3], [1, 2])); | |
console.log(intersection([], [1, 2])); | |
console.log(intersection([1], [3, 2])); | |
console.log(intersection([1], [3, 2, 1])); | |
console.log(intersection([4, 4, 4], [4, 4, 4])); | |
console.log(intersection([4, 4, 4, 5, 6], [4, 4, 4, 5])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment