intmin(int x, int y) { return x < y ? x : y; } voidmerge_sort(int arr[], int len) { int *a = arr; int *b = (int *) malloc(len * sizeof(int)); int seg, start; for (seg = 1; seg < len; seg += seg) { for (start = 0; start < len; start += seg * 2) { int low = start, mid = min(start + seg, len), high = min(start + seg * 2, len); int k = low; int start1 = low, end1 = mid; int start2 = mid, end2 = high; while (start1 < end1 && start2 < end2) b[k++] = a[start1] < a[start2] ? a[start1++] : a[start2++]; while (start1 < end1) b[k++] = a[start1++]; while (start2 < end2) b[k++] = a[start2++]; } int *temp = a; a = b; b = temp; } if (a != arr) { int i; for (i = 0; i < len; i++) b[i] = a[i]; b = a; } free(b); }
publicstatic List<int> sort(List<int> lst) { if (lst.Count <= 1) return lst; int mid = lst.Count / 2; List<int> left = new List<int>(); // 定义左侧List List<int> right = new List<int>(); // 定义右侧List // 以下兩個循環把 lst 分為左右兩個 List for (int i = 0; i < mid; i++) left.Add(lst[i]); for (int j = mid; j < lst.Count; j++) right.Add(lst[j]); left = sort(left); right = sort(right); return merge(left, right); } ///<summary> /// 合併兩個已經排好序的List ///</summary> ///<param name="left">左側List</param> ///<param name="right">右側List</param> ///<returns></returns> static List<int> merge(List<int> left, List<int> right) { List<int> temp = new List<int>(); while (left.Count > 0 && right.Count > 0) { if (left[0] <= right[0]) { temp.Add(left[0]); left.RemoveAt(0); } else { temp.Add(right[0]); right.RemoveAt(0); } } if (left.Count > 0) { for (int i = 0; i < left.Count; i++) temp.Add(left[i]); } if (right.Count > 0) { for (int i = 0; i < right.Count; i++) temp.Add(right[i]); } return temp; }
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14
defmerge list return list if list.size < 2
pivot = list.size / 2
# Merge lambda { |left, right| final = [] until left.empty? or right.empty? final << if left.first < right.first; left.shift else right.shift end end final + left + right }.call merge(list[0...pivot]), merge(list[pivot..-1]) end
defmergeSort(nums): iflen(nums) < 2: return nums mid = len(nums) // 2 left = mergeSort(nums[:mid]) right = mergeSort(nums[mid:])
i = j = 0 result = [] while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1
while i < len(left): result.append(left[i]) i += 1
while j < len(right): result.append(right[j]) j += 1
functionmergeSort(arr){ if(arr.length <=1) return arr; var middle = Math.floor(arr.length / 2); var left = arr.slice(0, middle); var right = arr.slice(middle); returnmerge(mergeSort(left), mergeSort(right)); }