Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to merge two sorted array in one sorted array in JavaScript without using sort()

Tags:

javascript

In this program merged two array and then sorted using temp.but this not correct method.because two array are sorted ,so method should be unique i.e. merging of two sorted in sorted form should be unique.

Example:

  • a=[1,2,3,5,9]
  • b=[4,6,7,8]

function mergeSortdArray(a,b){
	for(var i=0;i<b.length;i++){
		a.push(b[i]);
	}
	//console.log(a);
for(i=0;i<a.length;i++)
    {
        for(j=i+1;j<a.length;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    return a;
}
console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));
like image 451
Amit Modi Avatar asked Aug 10 '15 14:08

Amit Modi


Video Answer


3 Answers

Based on Eric Lundgren's answer above, but this fixes a couple of major bugs and is more efficient. Worked for me in production. I included using a sort function for more complex solutions - for this simple case you can just test for a > b as in Eric's answer if you want.

function mergeSortedArray(a, b) {
    var sorted = [], indexA = 0, indexB = 0;

    while (indexA < a.length && indexB < b.length) {
        if (sortFn(a[indexA], b[indexB]) > 0) {
            sorted.push(b[indexB++]);
        } else {
            sorted.push(a[indexA++]);
        }
    }

    if (indexB < b.length) {
        sorted = sorted.concat(b.slice(indexB));
    } else {
        sorted = sorted.concat(a.slice(indexA));
    }

    return sorted;
}

function sortFn(a, b) {
    return a - b;
}

console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));
like image 164
Dovev Hefetz Avatar answered Sep 18 '22 09:09

Dovev Hefetz


Hey I ran everyone's code from above against a simple .concat() and .sort() method. With both large and small arrays, the .concat() and .sort() completes in less time, significantly.

console.time("mergeArrays");
mergeArrays([1,2,3,5,9],[4,6,7,8])
console.timeEnd("mergeArrays");
//mergeArrays: 0.299ms

console.time("concat sort");
[1,2,3,5,9].concat([4,6,7,8]).sort();
console.timeEnd("concat sort");
//concat sort:0.018ms

With arrays of 10,000 size, the difference is even larger with the concat and sort running even faster than before (4.831 ms vs .008 ms).

What's happening in javascript's sort that makes it faster?

like image 29
David Lac Avatar answered Sep 18 '22 09:09

David Lac


How about something like this?

Since a and b are both sorted we only need to consider the top or first item of each array when adding. Note that this method will modify both a and b during execution, this may not be what you want, in which case you can add this code at the start:

var tempA = a.slice();
var tembB = b.slice();

This will make copies of the array which you can then use instead of a and b in the function below:

function mergeSortedArray(a,b){
    var tempArray = [];
    while(a.length || b.length) {
        if(typeof a[0] === 'undefined') {
            tempArray.push(b[0]);
            b.splice(0,1);
        } else if(a[0] > b[0]){
            tempArray.push(b[0]);
            b.splice(0,1);
        } else {
            tempArray.push(a[0]);
            a.splice(0,1);
        }
    }
    return tempArray;
}
console.log(mergeSortedArray([4,6,7,8], [1,2,3,5,9]));

Without using splice at all, try something like this:

function mergeSortedArray(a,b){
    var tempArray = [];
    var currentPos = {
        a: 0,
        b: 0
    }
    while(currentPos.a < a.length || currentPos.b < b.length) {
        if(typeof a[currentPos.a] === 'undefined') {
            tempArray.push(b[currentPos.b++]);
        } else if(a[currentPos.a] > b[currentPos.b]){
            tempArray.push(b[currentPos.b++]);
        } else {
            tempArray.push(a[currentPos.a++]);
        }
    }
    return tempArray;
}
console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));
like image 43
Erik Inkapööl Avatar answered Sep 19 '22 09:09

Erik Inkapööl