Reputation: 447
I can't seem to figure out what's wrong with my code. As the title says, I am trying to implement merge sort using integer vectors.
HEADER:
using Val = int;
using Container = std::vector<Val>;
using Iter = long;
void mergeSort(Container& arr, Iter start, Iter end);
.CPP (I've included the definition of merge in the file, just not pictured here)
void mergeSort(Container& arr, Iter start, Iter end) {
if (start >= end) return;
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, end, mid);
}
void merge(Container& arr, Iter start, Iter end, Iter mid)
{
int len = end - start + 1;
int x = 0;
Container temp;
temp.resize(arr.size());
int i, j, k;
i = start;
k = start;
j = mid + 1;
while (i <= mid && j <= end)
{
if (arr[i] < arr[j])
{
temp[k++] = arr[i++];
}
else
{
temp[k++] = arr[j++];
}
}
while (i <= mid) temp[k++] = arr[i++];
while (j <= end) temp[k++] = arr[j++];
for (k = 0; k < len; k++) arr[k + start] = temp[k];
}
many thanks!
Upvotes: 2
Views: 2152
Reputation: 4990
I think there might be four problems with your code.
<start,mid>
and <mid+1,end>
is sorted. If this condition does not hold (e.g. merge(v,0,3,2)
on {6,5,7,4}
) the algorithm will give incorrect results.end
value when using a function (e.g. merge(v,0,4,2)
on the array {6,5,7,4}
. You always have to iterate over <0,size-1>
.index
, not position
of the element in the array. For example merge(v,0,3,2)
would yield incorrect result on {1,6,2,4}
, because in the function you sort the sequence from index mid+1=2+1=3
to 3
, which contains only {4}
. Therefore, your first part {1,6,2}
is not sorted, which is required by your algorithm.The solution is to:
mid<end
.<0,mid>
and <mid+1,end>
using another sorting algorithm.Upvotes: 2
Reputation: 122
Only looking at your code, one problem I think is the initial value of k
in the merge
function.
If you put the temp value in the Container temp
starting from position 0
, then you should initialize k
to 0
k = 0;
Or if you want the position starting from start
, then you would need to change the last for
loop to
for (k = start; k <= end; k++) arr[k] = temp[k];
However, please post more information about the problem you encounter.. is it a Compilation Error? or a Runtime Error? or the result doesn't match your expectation? In addition, show what have you done to solve the problem:)
Upvotes: 1