merge 2 sorted arrays

merge 2 sorted arrays into 1 sorted array:


var arr_1 = [1, 3, 5];

var arr_2 = [2, 3, 6, 8];



function merge_2_sorted_arrays(arr_1, arr_2) {

    var i = 0,

        j = 0,

        k = 0,

        merged_arr = [];



    while (i < arr_1.length && j < arr_2.length) {

        if (arr_1[i] < arr_2[j]) {

            merged_arr[k] = arr_1[i];

            i++;

        } else {

            merged_arr[k] = arr_2[j];

            j++;

        }

        k++;

    }



    while (i < arr_1.length) {

        merged_arr[k] = arr_1[i];

        i++;

        k++;

    }



    while (j < arr_2.length) {

        merged_arr[k] = arr_2[j];

        j++;

        k++;

    }



    document.getElementById('input').innerHTML = 'Input sorted arrays: [' + arr_1 + ']; [' + arr_2 + ']';

    document.getElementById('output').innerHTML = 'Merged sorted array: [' + merged_arr + ']';



    //return merged_arr;

}



merge_2_sorted_arrays(arr_1, arr_2);

Leave a Comment