链表(免责声明:学校)据我所知如何排序合并与O(nlogn)时间和O(1)空间复杂度
,递归分割一个链表,然后发送它关闭另一个合并函数是O(nlogn)时间和O(n)空间。是否有可能在O(nlogn)时间和O(1)空间复杂度的链表上进行mergesort?你会如何去做这件事?
任何帮助表示赞赏
PS:确保传统归并为空间复杂度O(N),这是O(n)的一个例子,对不对?如何改变O(1)空间?
void sortTrack() {
Node merge = this.head;
this.head = Node (merge);
}
public Node mergeSort(Node head){
if ((head == null)||(head.next == null)){
return head;
}
Node left = head;
Node right = head.next;
while((right != null) && right.next != null){
head = head.next;
right = right.next.next;
}
right = head.next;
head.next = null;
return merge(mergeSort(left), mergeSort(right));
}
public Node merge(Node left, Node right){
Node head = new Node();
Node temp = head;
while((left != null) && (right !=null)){
if(left <= right){
temp.next = left;
temp = left;
left = left.next;
}
else{
temp.next = right;
temp = right;
right = right.next;
}
}
if(right == null)
temp.next = left;
else
temp.next = right;
return head.next;
}
感谢您的分解。你介意给我一个例子或者伪代码或者其他的东西吗?我不知道如何实施自下而上的方法 –
@RobBor:我已经为你添加了更多的细节。 – ruakh
@RobBor - wiki有一个[自下而上的链接列表合并排序]示例(https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists),它使用一个小的(25到32)固定大小的数组指针或内部工作列表的节点引用,这将被视为恒定的空间复杂度O(1)。 – rcgldr