我有一段需要解密的伪代码,我觉得我在正确的轨道上:
伪代码:
//initialize constant variable median=0.
//Sort the list as list.sort()
//Find the length of list as listlength=list.length
//if listlength is odd{
// find the middle number middle as Math.round(listlength-1)
// Now median=list[middle-1]
//}
//else{
// middle=list.length/2
// median=(list[middle]+list[middle-1])/2
//}
//print median on console using console.log(median)
请记住以上是伪代码!它需要被破译并变成Javascript!到目前为止,我正在发布我所拥有的内容!对此有任何帮助,正确方向上的一点是很好的
到目前为止我的代码:
使用Javascript:
var median = 0;
var sortList = list.sort(1,2,3,4,5,6,7,8,9,10,11);
if list.length =
在此之后我不知道还能做什么。我是否走在正确的轨道上?提前致谢。这是别人写的伪代码,我没有写。
答案 0 :(得分:1)
嗨,代码将是这样的:
<script>
var median = 0;
var middle;
var list = [4,3,2,1,5,6];
var listlength = list.length;
list.sort();
//if listlength even find the middle element
if (listlength%2 !== 0){
middle = Math.round(listlength-1);
median = list[middle-1];
// In my opinion should be
// middle = Math.round((listlength-1)/2);
// median = list[middle];
}
//if listlength is even find the arithmetic mean of 2 middle elements.
else{
middle = listlength/2;
median = (list[middle]+list[middle-1])/2;
}
console.log(median);
</script>
但我认为找到奇数的中位数的算法是错误的。当listlength为奇数时,它恰好足以打印列表的中间元素(如果数组被排序为c)。
答案 1 :(得分:0)
将其转换为步骤
//initialize constant variable median=0. Step 1
//Sort the list as list.sort() Step 2
//Find the length of list as listlength=list.length
//if listlength is odd{ Step 3
// find the middle number middle as Math.round(listlength-1) Step 4
// Now median=list[middle-1]
//}
//else{
// middle=list.length/2
// median=(list[middle]+list[middle-1])/2
//}
//print median on console using console.log(median) Step 5
然后您可以轻松将其转换为JavaScript
我不知道上面是哪种语言,也许是人类可读的算法。但它会是
var median = 0; // Step 1
var list = [1, 2, 3, 4, 5, 6];
list.sort(); // would execute on an Array only
if((list.length) % 2 == 0) { // Step 2 and 3
// even list
// do the even function to get median Step 4
} else {
// odd list
// do the odd function to get the median
}
document.write(median); // write the median! Step 5
我真的认为你需要学习JavaScript语法! :)它将进一步指导您如何工作。
对于排序方法:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort