Created
May 8, 2021 14:44
-
-
Save Amaka202/124e0c855e4ec1e2b69e2ee690ecea42 to your computer and use it in GitHub Desktop.
Algorithms Friday Solution for week 5
This file contains hidden or 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
// A school has two classes A and B. Each class has the ages of its students in | |
// a sorted list. | |
// The school decides to join both classes and needs you to help them write a function | |
// that merges both lists into one such that the students' ages still remain | |
// sorted in an increasing order | |
// PS: Do not use in buit sort function | |
const joinBothClasses = (classA, classB) => { | |
if(!classA) return []; | |
if(!classB) return classA; | |
if(!Array.isArray(classA)) return 0; | |
if(!Array.isArray(classB)) return 0; | |
let newClassList = []; | |
let classAIndex = 0 | |
let classBIndex = 0 | |
let currentIndex = 0 | |
while(currentIndex < (classA.length + classB.length)){ | |
let isClassAremaning = classAIndex >= classA.length; | |
let isClassBremaning = classBIndex >= classB.length; | |
if(!isClassAremaning && (isClassBremaning || (classA[classAIndex] < classB[classBIndex]))){ | |
newClassList[currentIndex] = classA[classAIndex] | |
classAIndex++ | |
}else{ | |
newClassList[currentIndex] = classB[classBIndex] | |
classBIndex++ | |
} | |
currentIndex++ | |
} | |
return newClassList; | |
} | |
joinBothClasses([13, 15, 19], [11, 13, 19]) // [11,13,13,15,18,19] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks alot Uduak!ππ»ππ»