0

我一直在努力让我的冒泡排序工作,现在它似乎陷入了无限循环。

我以为我正在适当地增加指针以解决这个问题,但似乎不是。如果有人能发现我的增量器应该去哪里让它适当地退出,那就太好了!

冒泡排序法:

public static void bubbleSort(DoubleLinkedList list) //static method used to sort the linked list using bubble sort
      {
          int i = 0;
          int j = 0;
          Node currentNode = list.head;
          Node previousNode = currentNode;
          Node tempNext =  currentNode;
          Node tempPrevious = currentNode;
          Node sentinelNode = currentNode;


          for(i=1; i<list.getSize(); i++)
          {

              while(sentinelNode.getNext() != null)
              {
                  if(currentNode.getData() > currentNode.getNext().getData())
                  {
                      if(currentNode == list.head)
                      {
                          Node tempNode = currentNode.getNext();

                          list.head = tempNode;
                          tempNext = tempNode.getNext();

                          tempNode.setNext(currentNode);
                          currentNode.setNext(tempNext);
                          currentNode.setPrevious(tempNode);

                          tempNext.setPrevious(currentNode);
                      }
                      else if(currentNode.getNext() == list.last)
                      {
                          Node tempNode = currentNode.getNext();
                          list.last = currentNode;
                          tempPrevious = currentNode.getPrevious();

                          tempNode.setNext(currentNode);
                          tempNode.setPrevious(tempPrevious);

                          currentNode.setPrevious(tempNode);
                      }
                      else
                      {
                          Node tempNode = currentNode.getNext();
                          tempPrevious = currentNode.getPrevious();
                          tempNext = currentNode.getNext();

                          tempPrevious.setNext(tempNode);
                          tempNext.setPrevious(currentNode);

                          currentNode.setNext(tempNext);
                          tempNode.setPrevious(tempPrevious);
                      }

                  }

                  sentinelNode = sentinelNode.getNext();

              }
          }


      }
4

1 回答 1

0

你的问题在你的 else 子句中。仔细看看你的设置。首先你有,

tempNode = currentNode.getNext();
tempNext = currentNode.getNext();

它们指向同一个对象。当你这样做时

currentNode.setNext(tempNode);

你没有改变任何东西,因为 tempNode 已经是 current.getNext();

正因为如此,您的 sentinelNode 在遍历 DoubleLinkedList 时遇到问题。

于 2012-09-26T04:23:03.367 回答