function sort(list) if list.length == 1 return list end if left = 取出從 list[0] 到 list[list.length / 2 - 1] right = 取出從 list[list.length / 2] 到 list[list.length - 1] return merge(sort(left), sort(right)) end function
function merge(left, right) var result = [] while left.length > 0 && right.length > 0 if right[0] < left[0] pop right 加到 result else pop left 加到 result end if end while left 剩下的加到 result right 剩下的加到 result return result end function
Bottom-up
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
function sort(list) // count 為每個已排序的子陣列長度,每次合併後每個已排序的片段長度都會加倍,故增量為乘 2 for count = 1; count < list.length; count *= 2 var work = [] // 每次取兩個片段來合併,故增量為兩個片段長度 for leftStart = 0; leftStart < list.length; leftStart += count * 2 rightStart = min(leftStart + count, list.length - 1) left = 取出從 list[leftStart] 到 list[rightStart - 1] right = 取出從 list[rightStart] 到 list[min(rightStart + count - 1, list.length)] // merge 同 Top-down merge(left, right) 加到 work end for list = work end for return list end function
privatestaticvoidMerge(int[] array, int[] workArray, int leftStart, int leftCount, int rightStart, int rightCount) { inti= leftStart, j = rightStart, leftBound = leftStart + leftCount, rightBound = rightStart + rightCount, index = leftStart; while (i < leftBound || j < rightBound) { if (i < leftBound && j < rightBound) { if (array[j] < array[i]) workArray[index] = array[j++]; else workArray[index] = array[i++]; } elseif (i < leftBound) workArray[index] = array[i++]; else workArray[index] = array[j++]; ++index; } for (i = leftStart; i < index; ++i) array[i] = workArray[i]; } }
C++
Top-down
TopDown.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef TOPDOWN_H #define TOPDOWN_H
classTopDown { public: staticvoidSort(int* array, int length); protected: private: staticvoidSort(int* array, int* workArray, int length, int start, int count); staticvoidMerge(int* array, int* workArray, int length, int leftStart, int leftCount, int rightStart, int rightCount); };
voidTopDown::Merge(int* array, int* workArray, int length, int leftStart, int leftCount, int rightStart, int rightCount) { int i = leftStart, j = rightStart, leftBound = leftStart + leftCount, rightBound = rightStart + rightCount, index = leftStart; while (i < leftBound || j < rightBound) { if (i < leftBound && j < rightBound) { if (array[j] < array[i]) workArray[index] = array[j++]; else workArray[index] = array[i++]; } elseif (i < leftBound) workArray[index] = array[i++]; else workArray[index] = array[j++]; ++index; } for (i = leftStart; i < index; ++i) array[i] = workArray[i]; }
Bottom-up
Bottom.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#ifndef BOTTOMUP_H #define BOTTOMUP_H
classBottomUp { public: staticvoidSort(int* array, int length); protected: private: staticvoidMerge(int* array, int* workArray, int length, int leftStart, int leftCount, int rightStart, int rightCount); };