【问题标题】:Insertion sort using Linked Integer Nodes使用链接整数节点的插入排序
【发布时间】:2013-05-07 03:06:33
【问题描述】:

嘿,我一直在尝试让插入排序方法为我正在学习的类工作,我们被告知使用插入排序对整数的链表进行排序,而不使用 Java 中已经存在的链表类图书馆。

这是我的内部 Node 类,因为我还没有完全掌握循环双向链表的概念,所以我只将其设为单链表

public class IntNode
{
  public int value;
  public IntNode next;
}

这是我在 IntList 类中的插入排序方法

public IntList Insertion()
{
IntNode current = head;

while(current != null)
    {
    for(IntNode next = current; next.next != null; next = next.next)
        {
        if(next.value <= next.next.value)
            {
            int temp = next.value;
            next.value = next.next.value;
                next.next.value = temp;
            }           
        }
    current = current.next;
    }
return this;
}

我遇到的问题是它根本没有排序它通过循环运行良好但根本没有操纵列表中的值有人可以向我解释我做错了什么我是初学者。

【问题讨论】:

  • 向我们展示一些结果样本
  • 这看起来不像insertion sort。此外,您的 if 测试似乎倒退了;你想按降序排序吗?
  • 他们告诉我们,无论是降序还是升序,我认为这很奇怪。在列表生成中,我向 main 方法传递了一个整数,例如 5,它将生成 0 到 5 之间的 5 个数字。列表与传入的相同。

标签: java linked-list insertion-sort


【解决方案1】:

您每次都需要从列表中的第一个节点开始,并且循环应该以列表的尾部 -1 结束 像这样

 public static IntList Insertion()
{
     IntNode current = head;
     IntNode tail = null;
     while(current != null&& tail != head )
     {
       IntNode next = current;
      for( ; next.next != tail;  next = next.next)
    {
    if(next.value <= next.next.value)
        {
        int temp = next.value;
        next.value = next.next.value;
            next.next.value = temp;
        }
    }
    tail = next;
   current = head;
  }
 return this;

}

【讨论】:

  • 谢谢你 aymankoo 和所有帮助你的人都很棒!
【解决方案2】:

仅当插入的列表已经排序时,插入操作才有效 - 否则您只是随机交换元素。首先,从原始列表中删除一个元素并从中构造一个新列表 - 这个列表只有一个元素,因此它是排序的。现在继续从原始列表中删除剩余的元素,随时将它们插入到新列表中。最后原始列表将为空,新列表将被排序。

【讨论】:

  • 我需要对我的代码进行哪些更改才能实现这一目标?除了创建我的列表类的新实例
  • 您的列表类需要能够在任意位置添加节点。您的 while 循环应该一直运行到原始列表为空;从原始列表中删除一个节点,然后使用 for 循环将其插入到新列表中。您不应该交换任何值,只能删除和插入节点。
【解决方案3】:

我也同意 Zim-Zam 的观点。 插入排序的循环不变量也指定了这一点:“按排序顺序的子数组”。 下面是我为插入排序实现的代码,其中我创建了另一个链表,其中包含按排序顺序的元素:

Node newList=new Node();
        Node p = newList;
        Node temp=newList;
        newList.data=head.data;
        head=head.node;
        while(head!=null)
        {
            if(head.data<newList.data)
            {
                Node newTemp = new Node();
                newTemp.data=head.data;
                newTemp.node=newList;
                newList=newTemp;
                p=newList;
            }   
            else
            {
                while(newList!=null && head.data>newList.data)
                {
                    temp=newList;
                    newList=newList.node;
                }
                Node newTemp = new Node();
                newTemp.data=head.data;
                temp.node=newTemp;
                newTemp.node=newList;
                newList=p;
            }

            head=head.node;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多