有序数组合并及等长数组对位穿插

将两个本身有序的数组合并为一个新的数组的方法

const arr1 = [11,15,18,23,26],
		arr2 = [11,19,21,25,27];

let mergeTwoArr = (arr1,arr2) =>{
	let u = 0, v = 0,//分别为两个数组的游标
	newArr = new Array();//新的数组

	while (u < arr1.length && v < arr2.length){
		if (arr1[u] <= arr2[v]) {
			newArr.push(arr1[u]);
			u ++;
		}else{
			newArr.push(arr2[v]);
			v ++;
		}
	}

	while (u < arr1.length){
		newArr.push(arr1[u]);
		u++;
	}

	while (v < arr2.length){
		newArr.push(arr2[v]);
		v++;
	}

	return newArr;
}

let interTwoArr = (arr1,arr2) =>{
	let j = 0,
	newArr = new Array();
	for(let i = 0; i < arr1.length; i++){
		j = i * 2;
		newArr[j] = arr1[i];
		newArr[j + 1] = arr2[i];
	}

	return newArr;
}


console.log("合并后的有序数组:", mergeTwoArr(arr1,arr2));
console.log("对位穿插后的数组:", interTwoArr(arr1,arr2));

打印结果:
在这里插入图片描述

你可能感兴趣的:(JS)