JavaScript ShellSort有些不对劲

时间:2018-06-17 12:13:03

标签: javascript arrays sorting



var CreateArray = (...lengths) => lengths.map(length => (
	Array.from({ length }, () => Math.floor(Math.random() * 3000000))
));
function compareNumeric(a, b) { 
	if (a > b) return 1;
	if (a < b) return -1;
}
var array8 = [];
for (var k= 0, t=100; k<t; k++){
	array8.push(Math.round(Math.random() * 3000000))
};
array8.sort(compareNumeric);

console.time("ShellSort")
function ShellSort(array) {
	var countOuter = 0;
	var countInner = 0;
	var countSwap = 0;
	function createGaps(a) {
		var gapss = [];
		for (var i = 0, j = a.length, t; 1 <= (t = Math.floor(j / Math.pow(2, i + 1))); i += 1) {
			gapss[i] = t;

			if (t === 1) {
				break;
			}
		}

		if (gapss[i] !== 1) {
			gapss.push(1);
		}
		return gapss;
	}
	var gaps = createGaps(array);
	for(var g = 0; g < gaps.length; g++) {
		var gap = gaps[g];
		for(var i = gap; i < array.length; i++) {
			countOuter++;
			var temp = array[i];
			for(var j = i; j >= gap && array[j - gap] > temp; j -= gap) {
				countInner++;
				countSwap++;
				array[j] = array[j - gap];
			}
			array[j] = temp;
		}
	}
	console.log('outer:', countOuter, 'inner:', countInner, 'swap:', countSwap);
}
console.timeEnd("ShellSort")

var ShellSortMultipleArrays = (arrs) => {
	arrs.forEach(arr => {
		console.time("ShellSort");
		ShellSort(arr);
		console.timeEnd("ShellSort");
	});
};


ShellSort(array8.slice())
var arrays = CreateArray(100,500,1000,5000,10000,50000,100000);
ShellSortMultipleArrays(arrays);
&#13;
&#13;
&#13;

我想通过炮弹对不同长度(100,500,1000,5000,10000,50000,100000)的阵列进行排序,但我不会理解,为什么它的长度为503,3506,8006,55005,120005, 700006,1500006?这里有什么问题?而且我也不明白这个&#34;差距&#34;在这里工作。任何想法如何解决?

0 个答案:

没有答案