自然合并链表

Mik*_*iko 6 sorting mergesort linked-list

我一直在寻找一个自然的 mergesort实现(链接列表)一段时间,但没有运气.

合并排序链接列表

这里我们有递归和迭代实现,但我不知道如何将其转换为自然合并.

在最佳情况下,如何检查运行以获得O(n)复杂度?它不一定是C/C++,可以是任何语言甚至是伪代码.

谢谢.

ulm*_*ngt 0

维基百科上有一个伪代码实现:

\n\n
 # Original data is on the input tape; the other tapes are blank\n function mergesort(input_tape, output_tape, scratch_tape_C, scratch_tape_D)\n     while any records remain on the input_tape\n         while any records remain on the input_tape\n             merge( input_tape, output_tape, scratch_tape_C)\n             merge( input_tape, output_tape, scratch_tape_D)\n         while any records remain on C or D\n             merge( scratch_tape_C, scratch_tape_D, output_tape)\n             merge( scratch_tape_C, scratch_tape_D, input_tape)\n\n # take the next sorted chunk from the input tapes, and merge into the single given output_tape.\n # tapes are scanned linearly.\n # tape[next] gives the record currently under the read head of that tape.\n # tape[current] gives the record previously under the read head of that tape.\n # (Generally both tape[current] and tape[previous] are buffered in RAM ...)\n function merge(left[], right[], output_tape[])\n     do\n        if left[current] \xe2\x89\xa4 right[current]\n            append left[current] to output_tape\n            read next record from left tape\n        else\n            append right[current] to output_tape\n            read next record from right tape\n    while left[current] < left[next] and right[current] < right[next]\n    if left[current] < left[next]\n        append current_left_record to output_tape\n    if right[current] < right[next]\n        append current_right_record to output_tape\n    return\n
Run Code Online (Sandbox Code Playgroud)\n