如果你想根据元素的对象属性Id值对Arr1进行排序,那么将排列好的数组Arr1放在Arr2中,最后Arr2将是:
var Arr2 = [{Id:1,Name:'Ajay1'},{Id:3,Name:'Ajay3'},{Id:5,Name:'Ajay5'},{Id:2,Name:'Ajay2'},{Id:4,Name:'Ajay4'}];
答案 0 :(得分:2)
除了吸引人的名字外,BubbleSort绝对没有什么值得推荐的。它不是最快的,它甚至不是最容易写的。
ExtractionSort和InsertionSort更快更容易编写。 (所有三种排序都需要与被排序的元素数量的平方成正比,但后两种排序的比例常数至少为两倍。)
这里的InsertionSort,定义为就地对阵列A进行排序。 (如果您不想就地排序,请先复制一份,然后就地复制。)
function InsertionSort(A) {
var N = A.length;
if (N < 2) { return; }
// Simplify the main loop by first moving the smallest element to the front
var leastInx = 0, leastID = A[0].Id;
for (var i = 1; i < N; ++i) { // note: i++ is cuter, but ++i is often faster
var thisID = A[i].Id; // avoid doing the same work twice
if (thisId < leastId]) {
leastInx = i; leastId = thisId; }}
var tmp = A[0];
A[0] = A[leastInx];
A[leastInx] = tmp;
// Now iterate over the remaining elements, inserting each in its
// proper place among the already-sorted previous elements
for (i = 2; i < N; ++i) {
tmp = A[i];
for (var j = i; A[j-1].Id > tmp.Id; --j) { // no need to test j>0
A[j] = A[j-1]; }
A[j] = tmp; }
}
当然,内置的排序将具有N log(N)的运行时间,这将吹走所有这些O(N ** 2)种类。编写自己的排序例程可能很有启发性,如果没有其他原因我会赞扬它,但如果你想要速度,可以利用专家的技能。
答案 1 :(得分:0)
我们可以使用bubble sort algorithm对Arr1进行排序或排列,然后迭代Arr2以将Arr1的排列元素迁移到Arr2。 在下面的解决方案中,我们不会使用任何本机方法进行排序,它只是循环和逻辑比较。
var Arr1 = [{Id:1,Name:'Ajay1'},{Id:5,Name:'Ajay5'},{Id:3,Name:'Ajay3'}];
var Arr2 = [{Id:3,Name:'Ajay3'},{Id:5,Name:'Ajay5'},{Id:1,Name:'Ajay1'},{Id:2,Name:'Ajay2'},{Id:4,Name:'Ajay4'}];
//var Arr1Res = [];
for (i = 0; i < Arr1.length; i++){
for (j = 0; j < (Arr1.length-1); j++){
if (Arr1[j].Id > Arr1[j+1].Id){
tmp = Arr1[j];
Arr1[j] = Arr1[j + 1];
Arr1[j + 1] = tmp;
}
}
}
// Migrating Arranged Arr1 to Arr2
for (x = 0; x < Arr2.length; x++){
for (y = 0; y < Arr1.length; y++){
if (Arr1[y].Id != Arr2[x].Id){
Arr2[y] = Arr1[y]
}
}
}
Arr1Res = Arr2 // You can replace Arr2 by Arr1 to check Arranged Arr1
for (k = 0; k < Arr1Res.length; k++){
alert(Arr1Res[k].Id+"---"+Arr1Res[k].Name)
}
查看以下DEMO: