简体   繁体   English

链表上的冒泡排序实现

[英]bubble sort implementation on linked lists

I have to implement a BubbleSort algorithm on a Linked List instead of an array. 我必须在链接列表而不是数组上实现BubbleSort算法。 I'm new to java so I don't really know how to put it in code. 我是Java的新手,所以我真的不知道如何将其放入代码中。 But I gave it a try and here's what I got: 但是我尝试了一下,这就是我得到的:

SinglyNode.java SinglyNode.java

public class SinglyNode
{
public Object names;
public SinglyNode next;

public SinglyNode (Object name1)
{
    names = name1;
}

public SinglyNode (Object name2, SinglyNode next1)
{
    names = name2;
    next = next1;
}

Object getObject()
{
    return names;
}

SinglyNode getNext()
{
    return next;
}

void displayLink()
{
    System.out.print("{" + names + "}");
}
}

LinkList.java I think my problem is here in the method. LinkList.java我认为我的问题在方法中。 I dunno how to implement the BubbleSort so it would sort the Object names in ascending order. 我不知道如何实现BubbleSort,因此它将以升序对对象名称进行排序。

public class LinkList
{
SinglyNode first;

public boolean isEmpty()
{
    return (first == null);
}

void insertFirst(Object name1)
{
    SinglyNode newNode1 = new SinglyNode(name1);
    newNode1.next = first;
    first = newNode1;
}

SinglyNode delete(Object name2)
{
    SinglyNode temp = first;
    first = first.next;
    return temp;
}

void display()
{
    System.out.print("LIST: \n");
    SinglyNode current = first;
    while(current != null)
    {
        current.displayLink(); // print data
        current = current.next; // move to next link
    }
    System.out.println("\n");
}
//////////////////////////////////////////////////////    
void bubbleSort()
{ 
    Object n = first;
    Object temp = first;

    if (na.compareTo(first) < first.compareTo(na))
    {
        temp = na.compareTo(first);
    } else {
        temp = first.compareTo(na);
    }
    System.out.println(temp);

}

private void swap(Object one, Object two)
{ 
    Object temp = one.names;
    one.names = two.names;
    two.names = temp; 
}
}

SinglyLinkList.java SinglyLinkList.java

public class SinglyLinkList
{
public static void main (String args[])
{
    LinkList list = new LinkList();

    list.insertFirst("Squirtle");
    list.insertFirst("Bulbasaur");
    list.insertFirst("Charmander");
    list.insertFirst("Pichu");
    list.insertFirst("Ghastly");
    list.insertFirst("Mewtwo");
    list.insertFirst("Dialga");

    list.display();
    list.bubbleSort();
    list.display();

}
}

In your list it will help to have a size field, to store the number of elements in the list. 在您的列表中,有一个size字段将有助于存储列表中的元素数量。 Also make the class SinglyNode implement Comparable so the compareTo method behaves as you want. 还应使SinglyNode implement ComparableSinglyNode implement Comparable以便compareTo方法表现出所需的效果。 The in-place swapping of two elements in Single LinkedList is actually quite involved, and the performance is really bad! 实际上,在Single LinkedList中交换两个元素确实很麻烦,而且性能确实很差!

public void bubbleSort
{
  for (int i = 0; i < size; i++)
  {
    for (int j = i; j < size; j++)
    {
       if (elementAt(j).compareTo(elementAt(j+1)) > 0)
       {
          swap(j, j + 1);
       }
    }
  }
}

public SinglyNode elementAt(int index)
{
   SinglyNode temp = first;

   for (int i = 0, i < index; i++)
   {
      temp = temp.getNext();
   }

   return temp;
}

public void swap(int firstIndex, int secondIndex)
{
   SinglyNode secondNext = elementAt(secondIndex).getNext();       
   SinglyNode second = elementAt(secondIndex);
   SinglyNode first = elementAt(first);
   SinglyNode firstPrevious = elementAt(first - 1);


   firstPrevious.setNext(second);
   first.setNext(secondNext);
   second.setNext(first);
}

You need to implement the Comparable interface in the SinglyNode and use the string compare method inside the implementation. 您需要在SinglyNode中实现Comparable接口,并在实现内部使用字符串compare方法。 Something like: 就像是:

public void compareTo(SinglyNode node){
    return this.names.toString.compareTo(node.getNames().toString());
}

Or better just this.names.compareTo(node.getNames()); 或者更好的是this.names.compareTo(node.getNames());

However instead of just use Object class, I would the use Comparable interface for those wildcard objects. 但是,我不只是使用Object类,而是将那些通配符对象使用Comparable接口。

1) You need to implement Comparable 1)您需要实现可比

2) You also need to use the swap method in bubblesort. 2)您还需要在Bubblesort中使用swap方法。 Currently you are not using this and it will only compare the two objects without swapping them in the actual list. 当前您没有使用它,它只会比较两个对象,而不会在实际列表中交换它们。

Use the tutorial for the Comparable 教程用于可比

Since it is homework/assignment, I will give a hint instead of direct solution. 由于这是家庭作业/作业,因此我将给出提示而不是直接解决方案。 Bubble sort can be abstracted to this two operations: iteration over collection and swapping elements. 冒泡排序可以抽象为这两个操作:集合上的迭代和交换元素。 Those operations are implemented differently with array or linked list, but the algoritm is the same. 这些操作是通过数组或链表实现的,但是算法是相同的。 You have iteration in display , now you need to implement swapping then do (very abstract pseudocode: display有迭代,现在需要实现交换,然后做(非常抽象的伪代码:

iterate {
 iterate {
  if el.Compare(elNext) > 0 {
    swap(el, el.Next);
  }
 }
}

Example linked list bubble sort that doesn't emulate random access using an elementAt() function, and instead operates via the links between nodes, so time complexity is O(n^2) instead of being much worse. 示例链表冒泡排序不使用elementAt()函数模拟随机访问,而是通过节点之间的链接进行操作,因此时间复杂度为O(n ^ 2)而不是更差。 "end" is used to keep track of where the sorted nodes at the end of the list begin. “结束”用于跟踪列表末尾的已排序节点的开始位置。 I used the example code from the question and didn't bother changing the class to comparable, using toString() instead for the compare. 我使用了问题的示例代码,并没有费心地将类更改为可比较类,而是使用toString()进行比较。 I used a dummy node to simplify the code. 我使用了一个虚拟节点来简化代码。

void bubbleSort()
{ 
    if(first == null)
        return;
    SinglyNode dmy = new SinglyNode("dummy");  // dummy node
    dmy.next = first;
    // end == null or first sorted node at end of list
    SinglyNode end = null;
    int swap;
    do{
        swap = 0;
        SinglyNode prv = dmy;           // previous node
        while(true){
            SinglyNode cur = prv.next;  // current node
            SinglyNode nxt = cur.next;  // next node
            if(nxt == end){             // if at end node
                end = cur;              //  update end = cur
                break;                  //  and break
            }
            // if out of order, swap nodes
            if(cur.names.toString().compareTo(nxt.names.toString()) > 0){
                cur.next = nxt.next;
                nxt.next = cur;
                prv.next = nxt;
                swap = 1;
            }
            prv = prv.next;             // advance to next node
        }
    }while(swap != 0);                  // repeat untl no swaps
    first = dmy.next;                   // update first
}

For bubble sort, both the loops must start from 0. Some versions of that algorithm start the inner loop at where the outer loop is. 对于冒泡排序,两个循环都必须从0开始。该算法的某些版本在外部循环所在的位置开始内部循环。 Doing so will cause issues for some data. 这样做会导致某些数据出现问题。

If ... you have an array with the following that you want sorted: 如果...,您有一个要排序的数组:

23,3,1,2,3,4,5 23,3,1,2,3,4,5

the sorted array if both loops start at 0 would be: 1, 2, 3, 3, 4, 5, 23 如果两个循环都从0开始,则排序数组为:1、2、3、3、4、5、23

But if the inner loop starts at j=i, the sorted array would be 23, 1, 2, 3, 3, 4, 5. This is because the inner loop moves on from the first element (which will be 3) after it puts 23 in the correct place and never figures out where to place 3 anymore 但是,如果内部循环从j = i开始,则排序后的数组将为23、1、2、3、3、4、5。这是因为内部循环从其后的第一个元素(将为3)继续前进将23放置在正确的位置,再也不会弄清楚放置3的位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM