complexity of mergesort with linked list

前端 未结 3 1130
死守一世寂寞
死守一世寂寞 2021-01-15 17:31

i have code for mergesort using linked list,it works fine,my question what is complexity of this algorithm?is it O(nlog(n))?also is it stable?i am interested because as i

3条回答
  •  一生所求
    2021-01-15 18:21

    How not to implement mergesort for linked lists

    • do not recursively bisect the list - random access isn't free
    • do not divide into sublists of size 1 and n - 1, as explained by ruakh

    How to implement mergesort for linked lists

    Instead of using bisection, build the lists up by maintaining a stack of already sorted sublists. That is, start by pushing lists of size 1 to the stack and merge down until you reach a list of greater size; you don't actually need to store the list sizes if you can figure out the math behind that.

    The sorting algorithm will be stable iff the merge function is. A stable version would build the merged list from scratch by always taking a single element from the lists, and using the first list in case of equality. An unstable, but better performing version would add to the merged list in chunks, avoiding unnecessary re-linking after each element.

提交回复
热议问题