2014-03-02 88 views
0

我有一种方法可以在内生双向链接列表中对卡片进行排序。插入排序内部卡片列表

public void sort(Comparator<Card> cmp) { 
// source code that I am adapting my code from 
//   for (int i=0; i < a.length; i++) { 
//     /* Insert a[i] into the sorted sublist */ 
//     Object v = a[i]; 
//     int j; 
//     for (j = i - 1; j >= 0; j--) { 
//      if (((Comparable)a[j]).compareTo(v) <= 0) break; 
//      a[j + 1] = a[j]; 
//     } 
//     a[j + 1] = v; 
//    } 

     for(Card f = first; f!=null; f = f.next){ 
      Card insert = f; 
      for(Card l = last; l!=null || l!= f; l = l.prev) 
      { 
       Card compare = l; 
       if(cmp.compare(compare, insert) <=0) 

        remove(insert); 
        this.add(insert); 
        break; 

      } 
     } 


     // Make sure to test invariant before and after 
     // You may find it helpful to use "remove" (but watch about size!) 
    } 

当我运行此代码时,它不正确排序。任何指针?

+0

你是通过调试器来学习的吗? –

回答

0

匆匆一瞥,我看到三个错误。可能还有更多。

  • 而不是l != null || l != f,我敢肯定你想&& - 你写的条件总是如此。
  • 您应该使用{}来划分if的“true”分支。目前,this.add(insert);break;会运行,无论if条件是否为真 - 并且您的缩进表明这不是您所期望的。
  • this.add(insert)中,您没有指定列表中添加新节点的位置。我希望看到一些指定您将在l指示的位置添加它的内容。