Why this code is not working?

Why this code is not working?

@cbcao263,
Your numbers are 0-indexed, but input is natural numbers.


Even now not working and don’t understand what will be the problem if I don’t follow the conditions that you mentioned above.

@cbcao263,
It’s not giving garbage values any more, you can now dry run to find the bug.
Use this,

Input
5 2
3 4 1 2 5

What I think is I am doing wrong there, I should not do the best_pos=n-i but it should be n-it->second

Sir not able to dry run this as you told array index will be 1 to n so the best_pos will be n-i that will be 5-5=0 and then I am swapping 2 values a[0] with a[5] but only one of them should exist, As If indexing starts from 0, 5 will not exist and if indexing starts from 1 to 5, 0 will not exist. And Please ignore the above comment, that was wrong.

@cbcao263,
Shouldn’t it be n-i+1 or n-i-1 for 1-indexed array…?

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.