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

后端 未结 24 945
我寻月下人不归
我寻月下人不归 2021-01-18 13:57

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 i

相关标签:
24条回答
  • 2021-01-18 14:19

    now you can do with es6 (...)spread operator

    ========================================
       using es6 (...)spread operator
    ========================================
    let a=[1,2,3,5,9]
    let b=[4,6,7,8]
    
    let sortedArray=[...a,...b].sort()
    console.log(sortedArray) 
    
    outputy :- [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    ========================================
           2nd way 
    ========================================
    
    
    function mergeSortedArray(a, b) {
        var sortedArray = [], indexA = 0, indexB = 0;
    
        while (indexA < a.length && indexB < b.length) {
            if (sortFuntion(a[indexA], b[indexB]) > 0) {
                sortedArray.push(b[indexB++]);
            } else {
                sortedArray.push(a[indexA++]);
            }
        }
    
        if (indexB < b.length) {
            sortedArray = sortedArray.concat(b.slice(indexB));
        } else {
            sortedArray = sortedArray.concat(a.slice(indexA));
        }
    
        return sortedArray;
    }
    
    function sortFuntion(a, b) {
        return a - b;
    }
    
    console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));
    output :- 1,2,3,4,5,6,7,8,9
    
    0 讨论(0)
  • 2021-01-18 14:22

    The issue I see with most solutions here is that they don't precreate the array, just pushing into an array when you know the end game size is a little bit wasteful.

    This is my suggestion, we can make it a little more efficient but it will make it less readable:

    function mergeSortedArrays(arr1, arr2) {
    		let i1 = 0, i2 = 0;
    		return [...arr1, ...arr2].map(
    			() =>
    				i1 === arr1.length ? arr2[i2++] :
    				i2 === arr2.length ? arr1[i1++] :
    				arr1[i1] < arr2[i2]? arr1[i1++] :
    				arr2[i2++]
    		);
    }
    
    console.log(mergeSortedArrays([1,2,3,5,9],[4,6,7,8]))

    0 讨论(0)
  • 2021-01-18 14:23

    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]));
    
    0 讨论(0)
  • 2021-01-18 14:23

    Lets implement a generic merger. Assuming that we don't know whether they are sorted ascending or descending we first need to apply a test to derive a compare function cf. Then it's a simple recursive walk as follows;

    function merger(a, b){
      var cf = a[0] < a[1] || b[0] < b[1] ? (x,y) => x < y
                                          : a[0] > a[1] || b[0] > b[1] ? (x,y) => x > y
                                                                       : (x,y) => false,
          mg = ([a,...as],[b,...bs]) => a !== void 0 &&
                                        b !== void 0  ? cf(a,b) ? [a].concat(mg(as,[b,...bs]))
                                                                : [b].concat(mg([a,...as],bs))
                                                      : a === void 0 ? [b,...bs]
                                                                     : [a,...as];
      return mg(a,b);
    }
    
    var a = [1,2,3,5,9,10,11,12],
        b = [4,6,7,8,17],
        c = [9,8,7],
        d = [23,11,10,4,3,2,1];
    
    console.log(merger(a,b));
    console.log(merger(c,d));

    Note: The tester to decide whether ascending or descending is sloppy. It doesn't even check equity of first two. It's just to give an idea. Implementing it properly is beyond the scope of this question.

    0 讨论(0)
  • 2021-01-18 14:23

    I needed it so implemented my ownn

    mergesortedarray(a, b) {
      let c = new Array(a.length+b.length);
      for(let i=0, j=0, k=0; i<c.length; i++)
        c[i] = j < a.length && (k == b.length || a[j] < b[k]) ? a[j++] : b[k++];
    }
    
    0 讨论(0)
  • 2021-01-18 14:25

    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]));

    0 讨论(0)
提交回复
热议问题