sorting - Merge Function for two arrays -
merge function 2 arrays, function not working , doesn't give required answer. want sorted arrays merged function saying, doesn't work.
var merge = function(array,array1,array2) { var n_array = array.length; var n_array1 = array1.length; var = j = k = 0; while(i < n_array && j < n_array1) { if(array[i] <= array2[j]) { array2[k] = array[i]; = + 1; } else { array2[k] = array1[j]; j = j + 1; } k = k + 1; } while(i < n_array) { array2[k] = array[i]; = + 1; k = k + 1; } while(j < n_array1) { array2[k] = array1[j]; j = j + 1; k = k + 1; } return array2; }; array = [1,3,5,7]; array1 = [2,4,6,8]; array2 = []; var result = merge(array,array1,array2); console.log("the array sorted " + result);
why code give answer: the array sorted 2,4,6,8,1,3,5,7
var merge = function(array,array1,array2) { var n_array = array.length; var n_array1 = array1.length; var = j = k = 0; while(i < n_array && j < n_array1) { if(array[i] <= array1[j]) { array2[k] = array[i]; = + 1; } else { array2[k] = array1[j]; j = j + 1; } k = k + 1; } while(i < n_array) { array2[k] = array[i]; = + 1; k = k + 1; } while(j < n_array1) { array2[k] = array1[j]; j = j + 1; k = k + 1; } return array2; }; array = [1,3,5,7]; array1 = [2,4,6,8]; array2 = []; var result = merge(array,array1,array2); console.log("the array sorted " + result);
it works :) edited solution op's problem.
Comments
Post a Comment