Javascript 在不同列表之间对项目进行排序的算法
我正在尝试实现一种算法,对相同列表或不同列表中的项目进行排序,并将结果保存到数据库中 在GUI中对项目进行排序的代码已经存在。 我正在使用jqueryui,它能够给我新职位的索引 示例1:Javascript 在不同列表之间对项目进行排序的算法,javascript,algorithm,jquery-ui,sorting,jquery-ui-sortable,Javascript,Algorithm,Jquery Ui,Sorting,Jquery Ui Sortable,我正在尝试实现一种算法,对相同列表或不同列表中的项目进行排序,并将结果保存到数据库中 在GUI中对项目进行排序的代码已经存在。 我正在使用jqueryui,它能够给我新职位的索引 示例1: 假设我在同一个列表中有两项。 如果我移动第一个项目而不是第二个项目,我可以得到值1(这是第二个项目的位置) 我使用javascript实现代码,但实际上我对伪代码很感兴趣 如果我必须对同一列表中的项目进行排序,那么故事就相当简单。 数据模型应如下所示: firstItem: { id: 5, next
假设我在同一个列表中有两项。
如果我移动第一个项目而不是第二个项目,我可以得到值
1
(这是第二个项目的位置)
我使用javascript实现代码,但实际上我对伪代码
很感兴趣
如果我必须对同一列表中的项目进行排序,那么故事就相当简单。数据模型应如下所示:
firstItem: {
id: 5,
next: 0
},
secondItem: {
id: 3
next: 1
}
item_0_1 = {
id: 13,
list_id: 0,
next: 0 // 1 -> 0 because the previous-one has been moved in another list
}
item_1_0 // does not change because I insert the item_0_0 after
item_1_1 = {
id: 35,
list_id: 1,
next: 2 // 1->2 it changes because I inserted the item_0_0 before
}
item_0_0 = {
id: 12,
list_id: 1, // 0->1 I need to change the list
next: 1 // this is the new position in the new list
}
当我移动firstItem
代替secondItem
时,我可以通过以下方式更改模型:
firstItem.prev = firstItem.next;
firstItem.next = newIndex;
secondItem.next = firstItem.prev;
示例2:假设我想在不同的列表之间对项目进行排序。
我想故事变得相当复杂:
模型应如下所示:
// list 1
item_0_0 = {
id: 12,
list_id: 0,
next: 0
}
item_0_1 = {
id: 13,
list_id: 0,
next: 1
}
// list 2
item_1_0 = {
id: 45,
list_id: 1,
next: 0
}
item_1_1 = {
id: 35,
list_id: 1,
next: 1
}
如果我在项_0_0
和项_1_0
之间移动项_0_0
,模型应如下所示:
firstItem: {
id: 5,
next: 0
},
secondItem: {
id: 3
next: 1
}
item_0_1 = {
id: 13,
list_id: 0,
next: 0 // 1 -> 0 because the previous-one has been moved in another list
}
item_1_0 // does not change because I insert the item_0_0 after
item_1_1 = {
id: 35,
list_id: 1,
next: 2 // 1->2 it changes because I inserted the item_0_0 before
}
item_0_0 = {
id: 12,
list_id: 1, // 0->1 I need to change the list
next: 1 // this is the new position in the new list
}
我的问题是,在这种情况下,更新列表的最佳代码是什么
这是我的伪代码:
item_0_0.list_id = newListID;
item_0_0.prev = item_0_0.next;
item_0_0.next = newIndex;
item_0_1.next = item_0_1.next - 1; // actually it should be iterated
// between all items after!
item_1_1.next = item_1_1.next + 1; // actually it should be iterated
// between all items after!
附言:1)
newIndex
和newListID
来自javascript库。2) 我认为在开始移动项目之前,列表已进行了良好的排序。如果需要解决方案,必须提供列表的代码/api。不,我们只知道数据。针对您的问题:假设两个列表都是有序的:从列表1中删除该项并修复两个相邻元素之间的gab,然后将该元素附加到另一个列表的前面/后面,并运行一个简单的循环以确定其位置。这将在最多
n
次迭代中起作用,但仅当列表有序时才起作用。newIndex
从何而来?在firstItem.next=newIndex中提到代码>和项目0\u 0.next=newIndex代码>@Ankush我将用您的评论更新我的问题。请参见页面的按钮。谢谢。@LorraineBernard好的。我不知道你在哪里分类?我看到的只是指针赋值或递增/递减代码。两者的比较在哪里?这是两个列表之间的某种合并排序吗?@Ankush我应该写一段代码。稍后我会更新这个问题。谢谢你的评论。