#001# 归并排序
2021-05-18 00:30
标签:js代码 pytho += init length solution ini ati directly js代码: Python代码: #001# 归并排序 标签:js代码 pytho += init length solution ini ati directly 原文地址:https://www.cnblogs.com/xkxf/p/9692307.html class MergeSort {
// merge two sorted sequences: arr[start:mid] and arr[mid:end]
static merge(arr, start, mid, end) {
let leftArr = arr.slice(start, mid); // arr[mid] is excluded
let rightArr = arr.slice(mid, end); // arr[end] is excluded
// put on the buttom of each pile a sentinel
// card, which contains a special value that
// we use to simplify our codes
let sentinel = Infinity;
leftArr.push(sentinel);
rightArr.push(sentinel);
let i = 0, j = 0; // index of leftArr and rightArr
for (let k = start; k k) {
arr[k] = leftArr[i] ];
}
}
// sort arr[start:end], arr[end] is excluded
static sort(arr, start, end) {
// calling sort(arr, 0, 1) doesn‘t make
// sense for there‘s only one element,
// so just stop dividing/recursive and merge directly.
if (start + 1 end) {
// divide the problem into two subproblems
let mid = Math.floor((start + end) / 2);
// recursively solve subproblems
MergeSort.sort(arr, start, mid);
MergeSort.sort(arr, mid, end);
// combine the solutions to the subproblems into
// the solution for the original problem.
MergeSort.merge(arr, start, mid, end);
}
}
static run(data) {
// convert a string to a numeric array
data = CommonUtil.handleData(data);
MergeSort.sort(data, 0, data.length);
console.log(data);
}
}
def merge(arr, start, mid, end):
left = arr[start:mid]
right = arr[mid:end]
sentinel = float(‘inf‘)
left.append(sentinel)
right.append(sentinel)
i = j = 0
for k in range(start, end):
if left[i] right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
def sort(arr, start, end):
if start + 1 end:
mid = int((start + end) / 2)
sort(arr, start, mid)
sort(arr, mid, end)
merge(arr, start, mid, end)
arr = [1, 3, 5, 2, 12, 3, 22, 88, 23]
sort(arr, 0, len(arr))
print(arr)
上一篇:多线程小总结
下一篇:阿里云短信接口开发实践(Java