As the "add/remove" item in the array?

0 like 0 dislike
7 views
The ordered real numbers A1, A2,..., An, a positive integer k and a real number P. Remove the element number k and paste in the sequence P, so the order is not broken


Made only for a particular case (for the specific array). If another array to use, the algorithm no longer works :(

Help:)
by | 7 views

1 Answer

0 like 0 dislike
Beware of pseudo-code.
Not tested, 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)
by

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
4 answers
0 like 0 dislike
2 answers
asked Jun 4, 2019 by polger
0 like 0 dislike
1 answer
asked Jun 5, 2019 by KUKI_CHAR
110,608 questions
257,186 answers
0 comments
28,659 users