Logic is correct but gives RE SWAPNUM31

Issue
My logic is long but correct. It gives Segmentation Fault. I made sure everything is in bounds but still RE.

My code

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    int t;
    cin>>t;
    while(t--){
        int n, k;
        cin>>n>>k;
        vector<int> arr;
        for(int i=0; i<n; i++){
        	int a;
            cin>>a;
            arr.push_back(a);
        }
        vector<int> temp;
        int i=0;
        while(i<n-k){
            temp.push_back(arr[i]);
            i++;
        }
        i=k;
        while(i<n){
            temp.push_back(arr[i]);
            i++;
        }
        sort(temp.begin(), temp.end());
        vector<int> ans;
        i=0;
        while(i<=temp.size()/2-1){
            ans.push_back(temp[i]);
            i++;
        }
        for(int j=n-k; j<k; j++){
            ans.push_back(arr[j]);
        }
        while(i<=temp.size()-1){
            ans.push_back(temp[i]);
            i++;
        }
        for(int j=0; j<n; j++){
            cout<<ans[j]<<" ";
        }cout<<endl;
    }
}

Problem Link: SWAPNUM31 Problem - CodeChef