Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is mergesort space complexity O(log(n)) with linked lists?

Tags:

Mergesort on an array has space complexity of O(n), while mergesort on a linked list has space complexity of O(log(n)), documented here

I believe that I understand the array case, because we need auxiliary storage when merging the two sub-arrays. But wouldn't a linked list merge sort just merge the two sub-linked lists in place? I think this would have space complexity O(1) for creating a new head.

In place merge (no auxiliary storage):

public Node merge(Node a, Node b) {     Node dummyHead, curr; dummyHead = new Node(); curr = dummyHead;     while(a !=null && b!= null) {         if(a.info <= b.info) { curr.next = a; a = a.next; }         else { curr.next = b; b = b.next; }         curr = curr.next;     }     curr.next = (a == null) ? b : a;     return dummyHead.next; } 

An explanation would be great.

like image 403
modulitos Avatar asked Jun 11 '14 19:06

modulitos


People also ask

Why is Mergesort space complexity n?

At first look, it makes sense that merge sort has space complexity of O(n) because to sort the unsorted array I'm splitting and creating subarrays but the sum of sizes of all the subarray will be n.

Why is Mergesort O n log n?

Mergesort is a divide and conquer algorithm and is O(log n) because the input is repeatedly halved.

Why is Mergesort good for linked lists?

It turns out that Mergesort works even better on linked lists than it does on arrays. It avoids the need for the auxiliary space, and becomes a simple, reliably O(N log N) sorting algorithm. And as an added bonus, it's stable too.

What is the big O complexity of mergesort?

Merge Sort is quite fast, and has a time complexity of O(n*log n) . It is also a stable sort, which means the "equal" elements are ordered in the same order in the sorted list. In this section we will understand why the running time for merge sort is O(n*log n) .


1 Answers

The mergesort algorithm is recursive, so it requires O(log n) stack space, for both the array and linked list cases. But the array case also allocates an additional O(n) space, which dominates the O(log n) space required for the stack. So the array version is O(n), and the linked list version is O(log n).

like image 192
Jim Lewis Avatar answered Mar 03 '23 22:03

Jim Lewis