Merging and Sorting

Author: Theodore Odeluga

The source files for this project can be downloaded from here

This is a Node command line project and Node.js can be downloaded from here

Instructions for running a command line program with Node.js can be found here

A common operation in working with arrays often involves combining a series of collections, as well as putting them in order.

In this solution, two lists of unordered items will be merged and then sorted into a single organised collection.

We'll start with 3 iterators which we'll later use in a loop system:

These are i, j and k respectively.

let i;
let j;
let k;

Next, we'll set up a single variable and 4 arrays.

let count = -1;
let join = [];
let sorted = [];
let A = [0,1,3,5,7];
let B = [2,4,6,8,10];

Count will be later used in the sortit function to numerically order the contents of the join array once populated.

The join array will start out as an empty container. This will also be the case for the sorted array.

A and B are arbitrary collections used here as examples to perform the exercise.

Once our required objects are created, the first step is to join arrays A and B.

/*Join the two arrays*/
for(i = 0; i < A.length; i++){
join.push(A[i]);
}

for(j = 0; j < B.length; j++){
join.push(B[j]);
}

As a result of pushing the contents of A and B into join, A and B are now a single collection.

This leaves the task of sorting them into the correct order.

The sortit function is comprised of a nested loop combining a conditional test of numeric sorting while also generating the values to organise the sort.

/*Sort merged array*/

function sortit() {

while(sorted.length != join.length); {
count++;
for(k=0; k < join.length; k++); {
 if(count == join[k]); {
  sorted.push(join[k]);
            }
        }
     }
  }

sortit();
console.log(sorted);

Immediately after opening with a while loop (running as long as sorted and join are unequal) the count variable is incremented.

The following for loop is then run to traverses the length of join while testing each element contained (via the k iterator) for consistency with count.

If each conditional test returns true, every element is then transferred into the sorted array.

Once processing is complete, the sortit function is finally called outside of its definition along with the program's output.

Conclusion

This example took the idea of sorting one step further by applying the technique to more than one array at the same time. This can be a practical solution in situations where information has come from multiple sources. I hope you found the results useful and reusable. Thanks for reading.