In the implementation below of mergesort, the input pointer inputIntArray
is somehow kept from being destroyed and winds up pointing to the sorted values pointed by sortedArray
. As it is, I thought inputIntArray
would not point to anything given the call delete[] intArray;
just before the last merge. Could anyone please shed some light on this? Thank you.
#include <iostream>
using namespace std;
int* getSubArray (int*,int,int);
int* merge(int*,int*,int,int);
int* mergeSort ( int* intArray , int n ) {
if (n==1){
return intArray;
}
else {
int m = n/2;
int* leftArray = mergeSort ( getSubArray (intArray,0,m-1) , m );
int* rightArray = mergeSort ( getSubArray (intArray,m,n) , n-m );
delete[] intArray;
return merge(leftArray,rightArray,m,n);
}
}
int* getSubArray ( int* intArray , int start , int end ){
int n = end - start + 1;
int * subIntArray = new int [ n ];
for (int i=0;i<n;i++){
subIntArray[i]=intArray[i+start];
}
return subIntArray;
}
int* merge(int* leftArray, int* rightArray, int m, int n){
int* intArray = new int[n];
int i=0 , j=0;
for (int k=0;k<n;k++){
if ( i == m && j == n ) {
break;
}
if (leftArray[i]<=rightArray[j] && i < m){
intArray[k]=leftArray[i++];
}
else {
intArray[k]=rightArray[j++];
}
}
delete[] leftArray;
delete[] rightArray;
return intArray;
}
int main () {
int* inputIntArray = new int[6]{1,5,6,2,3,7};
for (int i=0;i<6;i++){
cout << inputIntArray[i];
}
cout << endl;
int* sortedArray = mergeSort ( inputIntArray , 6 );
for (int i=0;i<6;i++){
cout << inputIntArray[i];
}
cout << endl;
for (int i=0;i<6;i++){
cout << sortedArray[i];
}
cout << endl;
delete[] sortedArray;
}
Here is the output:
156237
123567
123567
You have this call:
int* sortedArray = mergeSort(inputIntArray, 6);
In the process of executing that code, you do:
delete[] inputIntArray;
sortedArray = new int[6];
It is certainly possible that sortedArray
gets the same address as the just deleted inputIntArray
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.