我有一个递归算法的伪代码,可以找到数组中第k个最大的数字。伪代码使用从索引1开始的数组,但是当我实际编写代码时,我需要数组从索引0开始。我无法弄清楚如何调整算法来做到这一点。
var customer = function () {
var name = "Contoso";
return {
getName: function () {
return name;
},
setName: function (newName) {
name = newName;
}
};
}();
alert (customer.name);
我意识到不需要对算法进行任何更改,只需要进行初始调用。但是,当我这样做时,它并没有给我正确的价值。如果这是问题,这是我的实际代码:
Select-kth-Algorithm4(A: array [1…n] of n distinct integers; left, right, k: integers between 1 and n)
pivotIndex = a randomly generated integer such that left≤pivotIndex≤right
pivotNewIndex = partition(A, left, right, pivotIndex)
if pivotNewIndex−left≥k then
return Select-kth-Algorithm4(A, left, pivotNewIndex−1, k)
else if pivotNewIndex−left=k−1 then
return A[pivotNewIndex]
else
return Select-kth-Algorithm4(A, pivotNewIndex+1, right, k−pivotNewIndex+left−1)
//(Initial call to this algorithm should be Select-kth-Algorithm4(A,1, n, 5) for any particular value of n.}
partition(A, left, right, pivotIndex)
pivotValue = A[pivotIndex]
swap A[pivotIndex] and A[right]
storeIndex = left
for i = left to (right−1)
if A[i] > pivotValue then
swap A[storeIndex] and A[i]
storeIndex = storeIndex + 1
swap A[right] and A[storeIndex]
return storeIndex