【问题标题】:Bubble Sort on singly linked list Worst Time Complexity?单链表上的冒泡排序最糟糕的时间复杂度?
【发布时间】:2020-05-26 07:59:00
【问题描述】:

我知道单链表只指向下一个值而不能指向上一个值,所以我认为在冒泡排序中,列表的行为与仅包含在一个数组中的数组相同方向?如果是这样的话,时间复杂度会是O(n^2)吗?

【问题讨论】:

  • 是的,列表中的冒泡排序与数组中的冒泡排序具有相同的时间复杂度。而且时间复杂度是二次的。

标签: c++ time-complexity singly-linked-list bubble-sort


【解决方案1】:
#include <iostream> 

struct Node
{
    int data;
    struct Node* next;
} Node;


struct Node* swap(struct Node* ptr1, struct Node* ptr2)
{
    struct Node* tmp = ptr2->next;
    ptr2->next = ptr1;
    ptr1->next = tmp;
    return ptr2;
}


int bubbleSort(struct Node** head, int count)
{
    struct Node** h;
    int i, j, swapped;

    for (i = 0; i <= count; i++)
    {

        h = head;
        swapped = 0;

        for (j = 0; j < count - i - 1; j++)
        {

            struct Node* p1 = *h;
            struct Node* p2 = p1->next;

            if (p1->data > p2->data)
            {


                *h = swap(p1, p2);
                swapped = 1;
            }

            h = &(*h)->next;
        }


        if (swapped == 0)
            break;
    }
}
/* Function to print the list */
void printList(struct Node* n)
{
    while (n != NULL)
    {
        std::cout << n->data << " -> ";
        n = n->next;
    }
    std::cout << std::endl;
}

void insertAtTheBegin(struct Node** start_ref, int data)
{
    struct Node* ptr1
        = (struct Node*)malloc(sizeof(struct Node));

    ptr1->data = data;
    ptr1->next = *start_ref;
    *start_ref = ptr1;
}

//------------------------------------------- Driver Code 
int main()
{
    int arr[] = { 80,34,232,22,50,6 };
    int list_size, i;

    struct Node* start = NULL;
    list_size = sizeof(arr) / sizeof(arr[0]);

    for (i = 0; i < list_size; i++)
        insertAtTheBegin(&start, arr[i]);

    std::cout << "Linked list before sorting\n";
    printList(start);

    bubbleSort(&start, list_size);

    std::cout << "Linked list after sorting\n";
    printList(start);

    return 0;
}

正如您所见,列表中的冒泡排序确实与数组中的冒泡排序具有相同的时间复杂度,但唯一的区别是时间复杂度是二次的。

【讨论】:

  • 嗨!我对您的解释感到很困惑,这两种情况不是都有二次时间复杂度吗?
  • 两者具有相同的时间复杂度
  • @Monsi 一般来说,您在链表和数组中的交换方式相同,唯一的区别是您访问它的方式。所以显然时间复杂度是一样的。
【解决方案2】:

是的。

虽然您应该注意,对于单链表实现,您需要跟踪前一个指针以及交换操作,以处理下一个指针链接。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2015-05-17
  • 2015-06-15
  • 1970-01-01
  • 2015-08-20
  • 2016-02-23
相关资源
最近更新 更多