I'm unable to understand this problem , something is wrong with my code. please clear my doubt and tell me what is wrong in my code

#include<bits/stdc++.h>
using namespace std;
int binarysearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarysearch(arr, l, mid - 1, x);
return binarysearch(arr, mid + 1, r, x);
}
return -1;
}
int main () {
int n;
long long int k;
cin >> n;
cin >> k;
int* arr = new int[n + 1];
arr[0] = 0;
for(int i = 1 ; i <= n ; i++)
{
cin >> arr[i];
}
if(k >= n)
{
sort(arr + 1, arr+ n + 1 , greater());
}
else
{
int p = n;
int m = 1;
while(k > 0)
{

        if(arr[m] == p)
        {
            p = p - 1;
            m = m + 1;
        }
        else
        {
            int l = binarysearch(arr , m , n + 1 , p);
            int temp;
            temp = arr[m];
            arr[m] = arr[l];
            arr[l] = temp;
            p = p - 1;
            m = m + 1;
            k = k - 1;
        }
        
    }
}
for(int i = 1 ; i <= n ; i++)
{
    cout << arr[i] << "\n";
}
delete[] arr;
return 0;

}

You are applying Binary Search assuming that the sub array from the index where the element needs swapping to the end of the array is sorted.
Which is not true in this question.
Your assumption is taking the value of mid in binary search to more than the size of array thus causing segmentation fault.
Therefore, you are receiving runtime error.