1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 
  | 
function pMergeSort(input, done) {
	const spawn = require('threads').spawn;
	let arr=input;
	if (arr.length< 2){
		return arr;
	}
  
	function partition(arr) { 
	let middle = Math.floor(arr.length / 2);
	//var left = arr.slice(0, middle);
  //var right = arr.slice(middle + 1, arr.length); 
  return middle;
}
	
  let middle=partition(arr);
   let left=arr.slice(0, middle);
   let right=arr.slice(middle , arr.length);
	let task = spawn(pMergeSort(left,'done')).send(left).on('done', function (n) {
		if (result === undefined) {
			result=n;
		}else {
      result=merge(result, n);
     
			left.kill();
		}
	});
	pMergeSort(right), function (n) {
		if (result === undefined) {
      result=n;
			}
		else {
      result=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
}
//Test function t
function testParallel(){
	var array=genArray(10);
	pMergeSort(array,function(i){console.log(arr)});
	var testArr=genArray(10000)
	pMergeSort(testArr, function (i) {
	console.log(i);
});
	var testArr2=genArray(10000000)
	pMergeSort(testArr2, function (i) {
	console.log();
});
}
testParallel();
  |  |