如何在JavaScript中合并一个排序数组中的两个排序数组而不使用sort() [英] how to merge two sorted array in one sorted array in JavaScript without using sort()

查看:97
本文介绍了如何在JavaScript中合并一个排序数组中的两个排序数组而不使用sort()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个程序中合并了两个数组然后使用temp.but这个不正确的方法排序。因为两个数组是排序的,所以方法应该是唯一的,即两个以排序形式排序的合并应该是唯一的。



示例:




  • a = [1,2,3,5, 9]

  • b = [4,6,7,8]



< pre class =snippet-code-js lang-js prettyprint-override> function mergeSortdArray(a,b){for(var i = 0; i< b.length; i ++){a.push (双]); } //console.log(a);for(i=0;i<a.length;i++) {for(j = i + 1; j< a.length; j ++){if(a [i]> a [j]){temp = a [i]; A [1] = A [J]。一个[J] =温度;返回一个;} console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));

解决方案

嘿,我从上面对着一个简单的.concat()运行了每个人的代码。 sort()方法。对于大型和小型数组,.concat()和.sort()在更短的时间内完成。

  console。时间( mergeArrays); 
mergeArrays([1,2,3,5,9],[4,6,7,8])
console.timeEnd(mergeArrays);
// mergeArrays:0.299ms

console.time(concat sort);
[1,2,3,5,9] .concat([4,6,7,8])。sort();
console.timeEnd(concat sort);
// concat sort:0.018ms

对于10,000个大小的数组,差异是均匀的更大,concat和sort运行速度比之前更快(4.831 ms vs .008 ms)。



javascript的排序会让它变得更快?


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 in sorted form should be unique.

Example:

  • a=[1,2,3,5,9]
  • b=[4,6,7,8]

function mergeSortdArray(a,b){
	for(var i=0;i<b.length;i++){
		a.push(b[i]);
	}
	//console.log(a);
for(i=0;i<a.length;i++)
    {
        for(j=i+1;j<a.length;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    return a;
}
console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));

解决方案

Hey I ran everyone's code from above against a simple .concat() and .sort() method. With both large and small arrays, the .concat() and .sort() completes in less time, significantly.

console.time("mergeArrays");
mergeArrays([1,2,3,5,9],[4,6,7,8])
console.timeEnd("mergeArrays");
//mergeArrays: 0.299ms

console.time("concat sort");
[1,2,3,5,9].concat([4,6,7,8]).sort();
console.timeEnd("concat sort");
//concat sort:0.018ms

With arrays of 10,000 size, the difference is even larger with the concat and sort running even faster than before (4.831 ms vs .008 ms).

What's happening in javascript's sort that makes it faster?

这篇关于如何在JavaScript中合并一个排序数组中的两个排序数组而不使用sort()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆