Skip to content

Instantly share code, notes, and snippets.

@alialaba
Created May 9, 2021 11:30
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 alialaba/b27d641c07b3d1ab9f1a3c7e026cfdbb to your computer and use it in GitHub Desktop.
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
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();
@meekg33k
Copy link

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 that classA or classB cannot have null 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment