Почему выдает ошибку

Выдает вот такую ​​ошибку:HEAP CORRUPTION DETECTED:after Normal block(#3752) at 0x011203D0.
CRT detected that the application wrote to memory after end of heap buffer

#include <iostream>
#include<time.h>
#define N 1000
using namespace std;
int compares = 0, swaps = 0;

void Merge(int* A, int first, int last) {
    int middle, start, final, j;
    int* mas = new int[1000];
    middle = (first + last) / 2;  
    start = first;                
    final = middle + 1;           
    for (j = first; j <= last; j++) {
        swaps++;
        if ((start <= middle) && (final <= last))
        {
            compares++;
            mas[j] = (A[start] <= A[final])
                ? A[start++] : A[final++];
        }
        else {
            compares++;
                mas[j] = (start <= middle)
                ? A[start++] : A[final++];
        }
    }
    
    for (j = first; j <= last; j++) {
        swaps++;
        A[j] = mas[j];
    }
    delete[] mas;
};

void MergeSort(int* A, int first, int last) {
    if (first < last) {
        MergeSort(A, first, (first + last) / 2);  
        MergeSort(A, (first + last) / 2 + 1, last);  
        Merge(A, first, last);  
    }
}

int main() {
    setlocale(LC_ALL, "Rus");
    int i;
    int* A = new int[1000];
    srand(time(NULL));
    for (i = 0; i <= N; i++) {

        A[i] = rand();
    }
    cout << "First array: " << endl;
    for (i = 0; i <= N; i++) {
        cout << A[i] << " ";
    }
    MergeSort(A, 0, N);
    cout << "Sorted array: "<<endl;
    for (i = 0; i <= N; i++) {
        cout << A[i] << " ";
    }
    //cout << "compares=" << compares << endl;
    //cout << "swaps=" << swaps << endl;
    delete[] A;
    return 0;
}

Ответы (0 шт):