DEV Community

Nitin Sijwali
Nitin Sijwali

Posted on • Updated on

Merging two arrays and sort the resultant without sort functions using recursion in Javascript

Long ago, during an interview for one of the product-based companies, the interviewer asked me a DSA question, which triggered my sixth sense.

So the question was to merge two arrays and sort the resultant array in ascending order.
Example:-

const arr1 = [2,4,8,7, 10, 25, 17, 13, 12 ];
const arr2 = [1,4,6,9,8, 11, 13, 3, 0];
So I used spread operator to merge two arrays and  Array.sort() function to sort the values.
const resultant = [...arr1, ...arr2].sort((a, b) => a-b);
Enter fullscreen mode Exit fullscreen mode

This will give the desired result.

The interviewer then asked me not to use the sort function and to create one on my own, explaining that it would require two loops.
So I had to demonstrate the power of javascript to him, and I used recursion instead of two loops.

const result = [...arr1, ...arr2];
let count = 0;
function sorting(){
// to break the recursion when sorting is done.
if(count ===result.length) return true; 

//else do
for(let i = 0; i< result.length; i++){
  if(result[i] > result[i+1]){

//used array destructing to swap values
   [ result[i+1],  result[i]]= [result[i],result[i+1]]; 
  }
}
count++;
sorting();
}
sorting();
Enter fullscreen mode Exit fullscreen mode

In javascript, recursion is the most underappreciated concept. When DSA is used with javascript, this becomes quite strong. It can flatten arrays, objects, and construct tree structures like UI, among other things.

That's all for now, folks. Continue to learn and have faith in Javascript.

Top comments (0)