Created
May 9, 2021 11:30
-
-
Save alialaba/b27d641c07b3d1ab9f1a3c7e026cfdbb to your computer and use it in GitHub Desktop.
merged array list of students' ages that still remain sorted in increasing order
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
const sortedStudentAges=(classA, classB)=>{ | |
classA = [13,15,19]; | |
classB = [11,13,18]; | |
let combinedClass= [].concat(classA,classB); | |
let isItemSorted = false; | |
while(!isItemSorted){ | |
isItemSorted = true; | |
for(let i = 1; i < combinedClass.length; i++){ | |
//checking | |
if(combinedClass[i - 1] > combinedClass[i]){ | |
isItemSorted =false; | |
let sorted = combinedClass[i - 1]; | |
combinedClass[i - 1] = combinedClass[i]; | |
combinedClass[i]= sorted; | |
} | |
} | |
} | |
return combinedClass | |
} | |
sortedStudentAges(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @alialaba, thank you for participating in Week 5 of #AlgorithmFridays.
This is a decent attempt at solving the problem and I like your smart approach of concatenating both arrays and then sorting them. One of the things your solution fails to handle however is when one or both the classes has a
null
value.For example if I ran
sortedStudentAges([1, 2, 3], null)
, your solution would break on line 6 because you made an assumption thatclassA
orclassB
cannot havenull
values. Ideally, you always want to write robust code that can handle invalid or unexpected input without failing.I have written an article here about the importance of validating your assumptions when solving technical problems, you will find it helpful.
Thanks once again for participating!