维基百科上有一个伪代码实现:
\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