我不理解我在C++的归并排序中遇到的错误。

huangapple go评论64阅读模式
英文:

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; 是一个空的 vectorcin >> arr[i]; 写入了一个不存在的数组。

vector<int> arr; 改为 vector<int> arr(n);,以初始化具有 n 个元素的 vector

之后程序似乎在运行:https://godbolt.org/z/szvzeoxbW

英文:

vector&lt;int&gt; arr; is an empty vector. cin &gt;&gt; arr[i]; writes to a non existing array.

Change vector&lt;int&gt; arr; to vector&lt;int&gt; arr(n); to initialize the vector with n elements.

After that it looks like the program is running: https://godbolt.org/z/szvzeoxbW

huangapple
  • 本文由 发表于 2023年5月26日 15:44:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定