leetcode 148 sortList

来源:互联网 发布:专业看盘软件 编辑:程序博客网 时间:2024/05/16 18:56

题目:

主要是对链表进行排序,要求使用O(n log n)的时间复杂度,O(1)的空间复杂度。

联想常规的排序算法,一般有quicksort(),MergeSort(),堆排序这几种,其中quickSort排序的时间复杂度不够稳定,容易受初始值的影响;其次MergeSort()不能使用常数个单元(因为需要一个额外的N数组进行最后的归并,但是在链表中只用修改指针的链接而不需额外的内存),故选用合并排序。

选用的是C语言!其他的不太熟悉大笑

struct ListNode *Merge(struct ListNode* head,struct ListNode* middle){    struct ListNode *p,*p1=head,*p2=middle;    struct ListNode *tem=(struct ListNode *)malloc(sizeof(struct ListNode));    p=tem;    while(p1&&p2)    {        if(p1->val<=p2->val){p->next=p1;p=p->next;p1=p1->next;}        else{p->next=p2;p=p->next;p2=p2->next;}    }    if(p1)p->next=p1;    if(p2)p->next=p2;    head=tem->next;    return head;}struct ListNode *sortList(struct ListNode *head){    struct ListNode *p=head,*p1;    struct ListNode *front=head,*middle;    int n=0,i=0;//length of list    while(p)    {        n++;p=p->next;    }    printf("%d ",n);    if(n<2)return head;    else    {        p=head;        for( i=0;i<n/2;i++)            {                p1=p;                p=p->next;            }            p1->next=NULL;        middle=p;        front=sortList(front);        middle=sortList(middle);        head=Merge(front,middle);    return head;    }}
C++版参考feliciafay的博客

One of the main sources of efficiency in quicksort is locality of reference, where the computer hardware is optimized so that accessing memory locations that are near one another tends to be faster than accessing memory locations scattered throughout memory. The partitioning step in quicksort typically has excellent locality, since it accesses consecutive array elements near the front and the back. As a result, quicksort tends to perform much better than other sorting algorithms like heapsort even though it often does roughly the same number of comparisons and swaps, since in the case of heapsort the accesses are more scattered.

Additionally, quicksort is typically much faster than other sorting algorithms because it operates in-place, without needing to create any auxiliary arrays to hold temporary values. Compared to something like merge sort, this can be a huge advantage because the time required to allocate and deallocate the auxiliary arrays can be noticeable. Operating in-place also improves quicksort's locality.

When working with linked lists, neither of these advantages necessarily applies. Because linked list cells are often scattered throughout memory, there is no locality bonus to accessing adjacent linked list cells. Consequently, one of quicksort's huge performance advantages is eaten up. Similarly, the benefits of working in-place no longer apply, since merge sort's linked list algorithm doesn't need any extra auxiliary storage space.

That said, quicksort is still very fast on linked lists. Merge sort just tends to be faster because it more evenly splits the lists in half and does less work per iteration to do a merge than to do the partitioning step.



0 0
原创粉丝点击