1

基本上我有一个方法,它将采用任何一组具有选定值的数字,并按升序对它们重新排序,以跟踪新的选定值。

所以 {21, 2, 9, 13} selectedVal = 9 变成 { 1, 2, 3, 4 } selectedVal = 2

我现在需要做的是能够交换 2 个号码并保持订单不变。如果我想用 4 交换 2,我需要 3->2 和 4->3,但也需要反过来,比如用 1 交换 3,所以 1->2 和 2->3。

我确信有一个经过验证的算法,明天我可能会创建自己的有趣的算法,但我希望在我的实际应用程序中使用最快的解决方案。

算法的名称或任何有用的链接将不胜感激。如果这很重要,我正在使用 C# 4.0。

编辑 - 我想出了我自己的解决方案,我相信它在纸上有效,但如果有人知道更好的解决方案,我仍然希望得到答复。

假设有序列表总是从 1 开始,这在我的情况下......

if (newpos < currpos)
   for (int i = newpos-1; i < currpos-1; i++)
   {
       array[i] += 1;
       array[currpos-1] = newpos;
   }     
else if (newpos > currpos)
   for (int i = newpos-1; i >= currpos-1; i--)
   {
       array[i] -= 1;
       array[currpos-1] = newpos;
   }  
else // do nothing since they are trying to swap to the same place
4

0 回答 0