Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

算法必知必会:合并有序数组 #35

Open
pengjielee opened this issue Oct 31, 2019 · 0 comments
Open

算法必知必会:合并有序数组 #35

pengjielee opened this issue Oct 31, 2019 · 0 comments

Comments

@pengjielee
Copy link
Owner

1、实现

const merge = (arr1,arr2) => {
	let results = [];
	let index1 = 0, index2 = 0, current = 0;

	while( current < ( arr1.length + arr2.length ) ){
		let isArr1End = index1 > arr1.length
		let isArr2End = index2 > arr2.length

		if( !isArr1End && ( isArr2End || (arr1[index1] < arr2[index2]) ) ){
			results[current] = arr1[index1];
			index1++;
		}else{
			results[current] = arr2[index2];
			index2++;
		}
		current++;
	}
	return results;
}

2、测试

const arr1 = [3,8,9]
const arr2 = [2,4,6,10]
const results = merge(arr1,arr2)
console.log(results) //[2,3,4,6,8,9,10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant