Answer the question
In order to leave comments, you need to log in
How to "add/remove" an array element?
Given ordered real numbers A1, A2,..., An, a natural number k and a real number P. Remove the element with number k and insert it into the sequence P so that the order is not violated
Answer the question
In order to leave comments, you need to log in
Beware, pseudocode.
Didn't check, but the logic should work with any input array.
let input = [ a1, a2, ... , aN ] // ordered ascending, N > 1
let k, P // assume k > 0, 1-based indexing
// remove at k, 0-based indexing
for (let i = k; i < N; ++i)
input[i - 1] = input[i]
// insert P preserving order
for (let i = N - 1; i >= 0; --i) {
if (i == 0 || P >= input[i - 1]) {
for (let j = N - 1; j > i; --j)
input[j] = input[j-1]
input[i] = P
break
} else continue
}
// finish
print(input)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question