【问题标题】:How to sort a linked list using bubble-sort?如何使用冒泡排序对链表进行排序?
【发布时间】:2013-10-31 13:47:05
【问题描述】:

我正在尝试使用冒泡排序来对链表进行排序。我使用 curr 和 trail 来遍历列表。 curr 应该总是领先一步。到目前为止,这是我的代码:

void linked_list::sort ()
{
  int i,j=0;
  int counter=0;
  node *curr=head;
  node *trail=head;
  node *temp=NULL;

  while (curr !=NULL)
  {
    curr=curr->next;    //couting the number of items I have in my list. 
    counter++;          //this works fine.
  }

  curr=head->next;          // reseting the curr value for the 2nd position.

  for (i=0; i<counter; i++)
  {
    while (curr != NULL)
    {
      if (trail->data > curr->data)
      {
        temp=curr->next;      //bubble sort for the pointers.
        curr->next=trail;
        trail->next=temp;

        temp=curr;         //reseting trail and curr. curr gets back to be infront.
        curr=trail;     
        trail=temp;

        if (j==0)   //i'm using j to determine the start of the loop so i won't loose the head pointer.
        {
          head=trail;
        }

      }
      j++;
      trail=curr;
      curr=curr->next;   //traversing thru the list. nested loop.
    }

    trail=head;
    curr=trail->next;
    curr->next=trail->next->next;  //traversing thru the list. outer loop.
    j=0;
  }
}

我在这里错过了什么?

【问题讨论】:

  • 究竟是什么问题?
  • 您可以使用std::swap,并删除temp。顺便说一句,你应该把这个问题移到代码审查部分。

标签: c++ sorting pointers linked-list bubble-sort


【解决方案1】:

你错过了几件事;最重要的是链表不是数组,因此您不能轻松地对两者进行某些算法互换。请考虑以下几点:

  • 列表长度由到达最后一个节点来确定,但您不需要此算法。没有理由扫描列表只是为了找到您不需要的计数首先需要。当冒泡排序的最后一段到达单个节点(即它没有next 可以转到)时,您的“完成”状态就达到了。
  • 链表(或任何其他节点指针模式)的秘诀在于指针的操作。为此,您可以充分利用已经用于操作节点的东西:指针,但不仅仅是任何指针。 指向指针的指针
  • 永远不要低估一张纸和一支铅笔绘制出您希望算法如何工作的力量。特别是对于这样的事情:

现在看一下以下截然不同的方法。其中有一些东西对于理解整体算法至关重要,但我会在代码之后保存它:

void ll_bubblesort(struct node **pp)
{
    // p always points to the head of the list
    struct node *p = *pp;
    *pp = nullptr;

    while (p)
    {
        struct node **lhs = &p;
        struct node **rhs = &p->next;
        bool swapped = false;

        // keep going until qq holds the address of a null pointer
        while (*rhs)
        {
            // if the left side is greater than the right side
            if ((*rhs)->data < (*lhs)->data)
            {
                // swap linked node ptrs, then swap *back* their next ptrs
                std::swap(*lhs, *rhs);
                std::swap((*lhs)->next, (*rhs)->next);
                lhs = &(*lhs)->next;
                swapped = true;
            }
            else
            {   // no swap. advance both pointer-pointers
                lhs = rhs;
                rhs = &(*rhs)->next;
            }
        }

        // link last node to the sorted segment
        *rhs = *pp;

        // if we swapped, detach the final node, terminate the list, and continue.
        if (swapped)
        {
            // take the last node off the list and push it into the result.
            *pp = *lhs;
            *lhs = nullptr;
        }

        // otherwise we're done. since no swaps happened the list is sorted.
        // set the output parameter and terminate the loop.
        else
        { 
            *pp = p;
            break;
        }
    }
}

这与您可能预期的完全不同。这个简单练习的目的是确定我们正在评估数据,但我们实际上是在排序指针。请注意,除了p,它始终是列表的头部,我们没有使用额外的指向节点的指针。相反,我们使用指向指针的指针来操作隐藏在列表中的指针

为了演示该算法的工作原理,我编写了一个小型测试应用程序,该应用程序生成一个随机整数列表,然后在所述列表中将上述内容松散。我还编写了一个简单的打印实用程序来打印从任何节点到末尾的列表。

void ll_print(struct node *lst)
{
    while (lst)
    {
        std::cout << lst->data << ' ';
        lst = lst->next;
    }
    std::cout << std::endl;
}

int main()
{
    std::random_device rd;
    std::default_random_engine rng(rd());
    std::uniform_int_distribution<int> dist(1,99);

    // fill basic linked list
    struct node *head = nullptr, **pp = &head;
    for (int i=0;i<20; ++i)
    {
        *pp = new node(dist(rng));
        pp = &(*pp)->next;
    }
    *pp = NULL;

    // print prior to sort.
    ll_print(head);
    ll_bubblesort(&head);
    ll_print(head);
    return 0;
}

我还修改了原始算法,包括在每次通过交换某些内容后进行打印:

    *pp = *lhs;
    *lhs = nullptr;
    ll_print(p);

样本输出

6 39 13 80 26 5 9 86 8 82 97 43 24 5 41 70 60 72 26 95 
6 13 39 26 5 9 80 8 82 86 43 24 5 41 70 60 72 26 95 
6 13 26 5 9 39 8 80 82 43 24 5 41 70 60 72 26 86 
6 13 5 9 26 8 39 80 43 24 5 41 70 60 72 26 82 
6 5 9 13 8 26 39 43 24 5 41 70 60 72 26 80 
5 6 9 8 13 26 39 24 5 41 43 60 70 26 72 
5 6 8 9 13 26 24 5 39 41 43 60 26 70 
5 6 8 9 13 24 5 26 39 41 43 26 60 
5 6 8 9 13 5 24 26 39 41 26 43 
5 6 8 9 5 13 24 26 39 26 41 
5 6 8 5 9 13 24 26 26 39 
5 6 5 8 9 13 24 26 26 
5 5 6 8 9 13 24 26 
5 5 6 8 9 13 24 26 26 39 41 43 60 70 72 80 82 86 95 97

另一个示例

62 28 7 24 89 20 94 26 27 21 28 76 60 51 99 20 94 48 81 36 
28 7 24 62 20 89 26 27 21 28 76 60 51 94 20 94 48 81 36 
7 24 28 20 62 26 27 21 28 76 60 51 89 20 94 48 81 36 
7 24 20 28 26 27 21 28 62 60 51 76 20 89 48 81 36 
7 20 24 26 27 21 28 28 60 51 62 20 76 48 81 36 
7 20 24 26 21 27 28 28 51 60 20 62 48 76 36 
7 20 24 21 26 27 28 28 51 20 60 48 62 36 
7 20 21 24 26 27 28 28 20 51 48 60 36 
7 20 21 24 26 27 28 20 28 48 51 36 
7 20 21 24 26 27 20 28 28 48 36 
7 20 21 24 26 20 27 28 28 36 
7 20 21 24 20 26 27 28 28 
7 20 21 20 24 26 27 28 
7 20 20 21 24 26 27 
7 20 20 21 24 26 27 28 28 36 48 51 60 62 76 81 89 94 94 99 

请注意,一旦我们在不断减少的源列表中剩下一个已经排序的片段,我们就完成了。

总结

强烈建议使用调试器遍历上述算法,以更好地了解它的工作原理。事实上,无论如何,我建议使用大多数算法,但是执行指针到指针操作的算法可能有点令人生畏,直到你了解它的真正强大之处。这不是完成此任务的唯一方法,但如果您考虑如何管理链表以及您真正所做的只是更改存储在可预测位置的指针中的值,这是一种直观的方法。

【讨论】:

  • 您的评论很棒。非常有帮助。我正在尝试自己学习 c++,但有时会遇到死胡同。我想问你关于表达式:while (*pp)。这是否意味着循环会一直持续到 *pp 不存储地址?
  • @Reboot_87 表示直到 pp 指向指针的指针为 NULL。请记住,指针只不过是设计用来保存地址作为其值的变量。指向指针的指针只是另一个级别的间接。 IE。它包含一个指针的地址,该指针可能包含某物的地址。我通过取消引用来检查pp 寻址的指针,因此*pp
  • 这实际上是冒泡排序吗?因为你没有比较相邻的对
【解决方案2】:

基本上,这是一个修改后的排序。你的想法大多是正确的。主要是你搞砸了节点的指针交换。这是一个稍微简单的修改后的算法。在外层循环上是一个for 列表中元素的数量。然后内部循环是将值逐步推送到列表的末尾。我们跟踪两个指针trailcurr。我们比较currcurr-&gt;next

void linked_list::sort ()
{
  int count = 0, i;
  node *start = head;
  node *curr = NULL;
  node *trail = NULL;
  node *temp = NULL;

  while(start != NULL) { //grab count
    count++;
    start = start->next;
  }

  for(i = 0; i<count; ++i) { //for every element in the list

    curr = trail = head; //set curr and trail at the start node

    while (curr->next != NULL) { //for the rest of the elements in the list
      if (curr->data > curr->next->data) { //compare curr and curr->next

        temp = curr->next; //swap pointers for curr and curr->next
        curr->next = curr->next->next;
        temp->next = curr;

        //now we need to setup pointers for trail and possibly head
        if(curr == head) //this is the case of the first element swapping to preserve the head pointer
          head = trail = temp;
        else //setup trail correctly
          trail->next = temp;
        curr = temp; //update curr to be temp since the positions changed
      }
      //advance pointers
      trail = curr;
      curr = curr->next;
    }
  }
}

【讨论】:

    【解决方案3】:

    我想这就是你要找的:

    void BubbledSort_linked_list(struct Node **head)
    {
        Node * curr = *head;
        Node * next;
        int temp;
    
        while (curr && curr->next)
        {
    
            Node * next = curr->next;
            while (next)
            {
                if (curr->data > next->data)
                {
                    std::swap(next->data, curr->data);
                }
                next = next->next;
            }
            curr = curr->next;
        }
    }
    

    【讨论】:

      【解决方案4】:

      使用数组的冒泡排序可以很容易地修改为使用链表的冒泡排序

      // Using array
          for(int i=0;i<ar.length;i++){
              for(int j=0;j<ar.length-1;j++){
                  if(ar[j]>ar[j+1]){
                      int temp = ar[j];
                      ar[j]=ar[j+1];
                      ar[j+1] = temp;
                  }
              }
          }
      
      // Using linkedlist
          void bubblesortlinkedlist(Node head){
              Node i= head,j=head;
              while(i!=null){
                  while(j.next!=null){
                      if(j.data>j.next.data){
                          int temp = j.data;
                          j.data = j.next.data;
                          j.next.data = temp;
                      }
                      j=j.next;
                  }
                  j=head;
                  i=i.next;
              }
          }
      

      【讨论】:

        【解决方案5】:

        这是链表上冒泡排序的Java实现:

        • 时间复杂度:O(n^2)
        • 空间复杂度:O(1) - 冒泡排序是就地排序算法
        class Solution
        {
            public ListNode bubbleSortList(ListNode head)
            {
                boolean isSwapped = true;
        
                for(ListNode current = head, tail = null; isSwapped && head != tail; tail = current, current = head)
                {
                    for(isSwapped = false; current.next != tail; current = current.next) 
                    { 
                        if (current.val > current.next.val) 
                        {  
                            swap(current, current.next); 
                            isSwapped = true; 
                        }
                    }
                }
                return head;
            }
        
            private void swap(ListNode x, ListNode y)
            {
                if(x != y)
                {
                    int temp = x.val;
                    x.val = y.val;
                    y.val = temp;    
                }
            }
        }
        

        【讨论】:

        • 这个问题被标记为 C++,而不是 Java。
        猜你喜欢
        • 2017-09-27
        • 1970-01-01
        • 2016-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 2011-09-04
        • 1970-01-01
        相关资源
        最近更新 更多