我是并行处理编码的新手,正在尝试实现多线程合并排序算法。我不清楚线程的正确用法以及它如何工作,但是无论如何我都尝试实现它,这就是我着手的地方。 (告诉我切片不是函数)
function pMergeSort(input, done) {
const spawn = require('threads').spawn;
if (input.length< 2)
return input;
function partition(arr) {
let middle = Math.floor(arr.length / 2);
let left = arr.sclice(0, middle);
let right = arr.slice(middle + 1, arr.length);
}
let left,right=partition(input);
let task = spawn(pMergeSort).send(left).on('done', function (arr) {
if (result === undefined) {
for (let i = 0; i< n.length; i++) {
result[i] = n[i];
}
}else {
merge(result, n);
left.kill();
}
});
pMergeSort(right, function (n) {
if (result === undefined) {
for (let i = 0; i< n.length; i++) {
result[i] = n[i];
}
}else {
merge(result, n);
right.kill();
}
});
}
/*
function mergeSort (arr) {
if (arr.length === 1) {
// return once we hit an array with a single item
return arr
}
const middle = Math.floor(arr.length / 2) // get the middle item of the array rounded down
const left = arr.slice(0, middle) // items on the left side
const right = arr.slice(middle) // items on the right side
return merge(mergeSort(left), mergeSort(right))
}*/
// compare the arrays item by item and return the concatenated result
function merge(left, right) {
let result = []
let indexLeft = 0
let indexRight = 0
while (indexLeft < left.length && indexRight < right.length) {
if (left[indexLeft] < right[indexRight]) {
result.push(left[indexLeft])
indexLeft++
} else {
result.push(right[indexRight])
indexRight++
}
}
return result.concat(left.slice(indexLeft)).concat(right.slice(indexRight))
}
function genArray(size) {
// randomly fills arr
var arr = Array(size);
for (var i = 0; i < size; i++) {
arr[i] = Math.floor(Math.random() * 98);
}
return arr
}
function testParallel(){
var array=genArray(Math.floor(Math.random()*100));
pMergeSort(array, function(i){
console.log(JSON.stringify(i));
})
}
var testArr = genArray(2);
pMergeSort(testArr, function (i) {
console.log(JSON.stringify(i));
});
帮助实现这一点将是惊人的,但是一些可能将我推向正确方向的简单问题是,pMergeSort
的合并是否应该是回调函数?您如何定义回叫功能?使用线程池而不是尝试生成线程会更好吗?并且包装在pMergeSort中的函数应该是归并排序+拆分为线程吗?