Median of two sorted arrays

#include
using namespace std;
#include
#include
#include
int main(){
int n; int a[1000]; int b[1000];
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
for(int i=0;i<n;i++) cin>>b[i];
//merge sort of the two arrys
int i=0,j=0;
vectorc; int k=0;
//merged array
while(i<n && j<n){
if(a[i]<b[i]) c[k++]=a[i++];
else c[k++]=b[j++];
}
// Copy the remaining elements of array a, if any
while (i < n) c[k++] = a[i++];

// Copy the remaining elements of array b, if any
while (j < n) c[k++] = b[j++];

if(c.size()%2!=0) cout<<c[c.size()/2];
return 0;
}

Segmentation fault is occurring at line 17. Why??

#include using namespace std; #include #include #include int main(){ int n; vector a(n); vector b(n); cin>>n; for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<n;i++) cin>>b[i]; //merge sort of the two arrys int i=0,j=0,count=0; while(i<n && j<n){ if(a[i]<b[i]) i++; else j++; count++; if(count==n) break; } cout<<(a[i]+b[j])/2; return 0; } Even this is returning segmentation fault. please explain.

The segmentation fault occurs because the comparison in line 17 should be if(a[i] < b[j]) instead of if(a[i] < b[i]) . The current code incorrectly accesses b[i] , leading to out-of-bounds access when i is greater than n-1 .

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.