英文:
I do not understand the error I am getting in Merge sort in C++
问题
I am learning the Merge sorting technique and wrote this code by following a tutorial. However, I am getting an error here. I would like to understand the mistakes, I am doing here.
使用在线编译器时,遇到分段错误,而在本地,则发现操作符不匹配的错误。
英文:
I am learning the Merge sorting technique and wrote this code by following a tutorial. However, I am getting an error here. I would like to understand the mistakes, I am doing here.
On using online compiler I encountered Segmentation error, while locally, error like operator not matching is found.
#include <bits/stdc++.h>
using namespace std;
void merge(vector<int> &arr, int low, int mid, int high){
    vector<int> temp;
    int left=low;`enter code here`
    int right=mid+1;
    while (left<=mid && right<=high)
    {
        if(arr[left]<=arr[right]){
            temp.push_back(arr[left]);
            left++;
        }
        else{
            temp.push_back(arr[right]);
            right++;
        }
    }
    while(left<=mid){
        temp.push_back(arr[left]);
            left++;
    }
    while(right<=high){
        temp.push_back(arr[right]);
        right++;
    }
    for(int i=low;i<=high;i++){
        arr[i]=temp[i-low];
    }
}
void mS(vector<int> &arr, int low, int high){
    if(low>=high) return;
    int mid=(low+high)/2;
    mS(arr, low, mid);
    mS(arr, mid+1, high);
    merge(arr, low, mid, high);
}
void mergeSort(vector<int> &arr, int n){
    mS(arr, 0, n-1);
}
int main()
{
    int n;
    cin >> n;
    vector<int> arr;
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    mergeSort(arr, n);
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
}
答案1
得分: 2
vector<int> arr; 是一个空的 vector。cin >> arr[i]; 写入了一个不存在的数组。
将 vector<int> arr; 改为 vector<int> arr(n);,以初始化具有 n 个元素的 vector。
之后程序似乎在运行:https://godbolt.org/z/szvzeoxbW
英文:
vector<int> arr; is an empty vector. cin >> arr[i]; writes to a non existing array.
Change vector<int> arr; to vector<int> arr(n); to initialize the vector with n elements.
After that it looks like the program is running: https://godbolt.org/z/szvzeoxbW
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论