I made a program to merge and sort, but the arrangement that I should have made changes to comes back.After a lot of research, when the array that should have been rearranged in merge returned to recMergeSort, it was returned before the change.I think the reason is that the array is not well received, but I don't know what's wrong.
main.cpp
#include<iostream>
# include "recFunc.h"
using namespace std;
int main() {
constint NUM_VALUES=8;
int mergeArray [NUM_VALUES] = {6,3,5,1,8,2,4,8};
// show starting array
cout<<"Starting array is"<<endl;
for (inti=0;i<NUM_VALUES;i++)
cout<<mergeArray[i]<";
cout<<endl;
// now sort it
mergeSort(mergeArray, NUM_VALUES);
// show updated array, should be in ascending order
cout<<"Now the array should be sorted"<<endl;
cout<<"expected:1 2 3 4 5 678" <endl;
cout<<"actually:";
for (inti=0;i<NUM_VALUES;i++)
cout<<mergeArray[i]<";
cout<<endl;
cout<<endl<<"Done with testing merge sort"<<endl<endl;<
return 0;
}
recFunc.cpp
#include<iostream>
# include "recFunc.h"
void mergeSort(int*array, int size)
{
recMergeSort(array,size);
}
void recMergeSort(int*array, int size)
{
if(size<=1)
{
return;
}
int middle=(size-1)/2;
int*arrayLeft = new int [middle+1];
int*arrayRight=new int [(size-1)-middle];
for (inti=0; i<middle+1;i++)
{
arrayLeft[i] = array[i];
}
for (inti=0;i<(size-1) - middle;i++)
{
arrayRight[i] = array[(middle+1)+i];
}
recMergeSort(arrayLeft, middle+1);
recMergeSort(arrayRight, (size-1)-middle);
int*temp=merge(arrayLeft, middle+1, arrayRight, (size-1)-middle);
array=temp;
}
int*merge(int*arrayLeft, int leftSize, int*arrayRight, int rightSize)
{
int left = 0;
int right = 0;
int leftEnd = leftSize-1;
int rightEnd = rightSize-1;
int*temp = new int [leftSize + rightSize];
while(left<=leftEnd&&right<=rightEnd)
{
// if left value is smaller, save the value to temp
if (arrayLeft [left] <=arrayRight [right])
{
temp [left+right] = arrayLeft [left];
left++;
}
// otherwise (right value is small), save it
else
{
temp[left+right] = arrayRight[right];
right++;
}
}
while(left<=leftEnd)
{
temp [left+right] = arrayLeft [left];
left++;
}
while(right<=rightEnd)
{
temp[left+right] = arrayRight[right];
right++;
}
return temp;
}
recFunc.h
int*merge(int*arrayLeft, int leftSize, int*arrayRight, int rightSize);
void recMergeSort(int*array, int size);
void mergeSort(int*array, int size);
void recMergeSort (int*array, int size)
{
...
array=temp;
Changing the argument array
does not change the array that array
points to. Copy the contents of temp
one element at a time to where array
points, or pass array
to the function.
© 2024 OneMinuteCode. All rights reserved.