简体   繁体   English

单链表上的冒泡排序最糟糕的时间复杂度?

[英]Bubble Sort on singly linked list Worst Time Complexity?

I know that a singly linked list only points to the next value and cannot point to the previous value, so am I right to think that in a bubble sort the list would act the same as an array where it only goes in one direction?我知道单链表只指向下一个值而不能指向前一个值,所以我认为在冒泡排序中,列表的行为与仅在一个方向上的数组相同吗? If that was the case would the time complexity be O(n^2)?如果是这种情况,时间复杂度会是 O(n^2) 吗?

#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;
}

As you can see indeed a bubble sort in a list has the same time complexity as a bubble sort in an array but the only difference is that the time complexity is quadratic.正如您所看到的,列表中的冒泡排序确实与数组中的冒泡排序具有相同的时间复杂度,但唯一的区别是时间复杂度是二次的。

Yes it would be.是的。

Although you should note that for singly linked list implementation, you will need to keep track of the previous pointer as well for the swap operation, to handle the next pointer links.尽管您应该注意,对于单链表实现,您还需要跟踪前一个指针以进行交换操作,以处理下一个指针链接。

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

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