更新时间:2022-12-09 17:12:31
嘿,我从上面对着一个简单的.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?