Sorted Merge

In this example below you will see how to do a Sorted Merge with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by ksepehri, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright ksepehri ©
  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Sorted Merge</title>
  
  
  
  
  
</head>

<body>

  
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/ksepehri/sorted-merge-Lxggre */
function sortedMerge(a,b) {
  if(!a.length && !b.length) return null;
  if(!b.length) return a;
  if(!a.length) return b;
  let shorter = (a.length < b.length) ? a : b;
  let longer = (a.length < b.length) ? b : a;
  
  let result = longer.slice();
  
  for(let i=0; i<result.length; i++) {
    if(!shorter.length) return result;
    let arr = [];
    while(result[i] >= shorter[0]) {
      arr.push(shorter.shift());
    }
    
    if(arr.length) {
      result.splice(i,0,...arr);
      i += arr.length;
    }
  }
  
  if(shorter.length) {
    result = result.concat(shorter);
  }
  
  return result;
}

const a = [1,4,6,7,8];
const b = [0,2,3,5,8,9,60];

console.log(sortedMerge(a,b));

Comments