【发布时间】:2016-05-16 22:41:09
【问题描述】:
我编写了一个解决方案来获取通过表单输入的整数列表。有用。它为您提供两个最大整数的总和并将其发布到 DOM 中。 但是,对于 100 万个整数的大型数组,它的效率不是很高。
如何改进此解决方案以提高效率。
App.js
// This function reverses the order of the array and places the biggest numbers first
function sortNumber(a, b) {
return b - a;
}
// this function is used to ensure the user didn't enter any letters
function getArray() {
var alphaExp = /^[a-zA-Z]+$/;
// This function takes the array, orders it, adds the sum of the two largest numbers and returns the value
function sumOf(x) {
// Sort the ary with the sortNumber function
array.sort(sortNumber);
// Then we add the two biggest numbers of the array and save it to the result variable.
var result = array[0] + array[1];
// Then we share the result with the user by updating the browser
var myHeading = document.querySelector('h2');
myHeading.textContent = "The sum of your two biggest numbers is: " + result;
// Like a good student, it's important to show your work
var showYourWork = document.querySelector('h3');
showYourWork.textContent = array[0] + " + " + array[1] + " = " + result;
}
// This grabs the value of the input
var arrayField = document.getElementById('arrayField').value;
if (arrayField.match(alphaExp)) {
// Fail if user enters letters
var raiseError = document.querySelector('h5');
raiseError.textContent = 'No not letters! We want numbers!!';
} else {
var array = JSON.parse("[" + arrayField + "]");
if (arrayField.length < 2) {
// If the user enters only 1 number, tell them to enter more!
var raiseError = document.querySelector('h5');
raiseError.textContent = 'Please enter atleast two numbers seperated by commas for us to add!'
} else {
// When the user enters a list of numbers, run the sumOf function.
sumOf(arrayField);
//Make the error go away
var raiseError = document.querySelector('h5');
raiseError.textContent = '';
}
}
};
// use an eventlistener for the event (This is where the magic happens)
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getArray, false);
【问题讨论】:
-
“效率不高”到底是什么意思?内置排序功能是一种很好的高效排序。您可能可以使用专门构建的基数排序做得更好,具体取决于输入值的性质。
-
我指的是处理能力。我对 sort 函数的解释是,每次遇到一个并非紧接在前一个值之前的整数时,它都必须返回数组,如果它必须对一百万个整数进行排序,这似乎相当低效。跨度>
-
不,排序是一个算法领域,已经被广泛研究了 60 或 70 年(甚至更长时间)。
.sort()方法确实必须做一些工作来对数组进行排序,但请确信它非常有效。现在,如果您只需要提取两个顶部(或底部)值,则无需排序即可。 -
您真的需要一个排序列表,还是仅仅确定两个最大的数字就足够了? (因为完全排序一百万个数字只是为了找到最大的两个听起来是一种非常低效的方法。)
-
可以使用TypedArray吗?
标签: javascript arrays performance sorting