(C++) 안녕하세요, 이것은 mergesort에서 처음 시도한 것입니다. 이전 질문을 게시 한 사람과 비슷한 코드를 보았습니다 : here. 하위 수준에서는 정렬이 예상대로 작동합니다. 그러나 여기에서 내 문제는 정렬 된 배열이 각 하위 수준 이후에 범위를 벗어나서 올바르게 정렬되지 않는다고 생각합니다. 이 경우, "std :: vector &"을 사용하여 참조로 전달하려고했습니다. 내가 잘못? 참조로 전달하는 적절한 방법은 무엇입니까? 당신은 당신이 강조 스레드에서 본 코드를 모방하려는 경우, 코드는 포인터를 사용하고 있습니다C++ : Mergesort 문제 : 범위를 벗어 났습니까?
/*
MERGE SORT
breaking down the sorting into pairs concursively until we are comparing only two values
The two integers parameters denotes indices for beginning and ending values in vector
Merge sort inclusive of both left and right range
*/
#include <vector> // for using vectors in c++
void merge(std::vector<int>& inputv, int beg_i, int end_i)
{
int d = beg_i; // used as an index
int e = beg_i + (end_i - beg_i)/2 + 1; // used as an index
int y = beg_i + (end_i - beg_i)/2; // used as a check against d
int z = end_i; // used as a check against e
std::vector<int> tempvect(inputv.size());
for (int c = beg_i; c < z+1; c++)
{
if (e > z && d > y)
{
// do nothing
}
else if (e > z)
{
tempvect[c] = inputv[d];
d++;
}
else if (d > y)
{
tempvect[c] = inputv[e];
e++;
}
else if(inputv[d] > inputv[e])
{
tempvect[c] = inputv[e];
e++;
}
else if(inputv[d] <= inputv[e])
{
tempvect[c] = inputv[d];
d++;
}
}
for (int i = beg_i; i < end_i+1; i++)
{
inputv[i] = tempvect[i];
}
}
void mergesort(std::vector<int> inputvector, int beg_i, int end_i)
{
if(end_i - beg_i == 0)
{
// do nothing
}
if(end_i - beg_i >= 1)
{
int mid_i = beg_i + (end_i - beg_i)/2;
mergesort(inputvector,beg_i,mid_i); // reclusive to last card
mergesort(inputvector,mid_i+1,end_i); // resulsive to last card
merge(inputvector,beg_i,end_i); // actual implementation to sort and merge the vectors
}
}
안녕하세요 PaulMcKenzie, 아니요. 코드를 복사하려고하지 않았으며,이 코드를 생각해 냈습니다. 다른 사람들이 어떻게 코드를 작성하는지 보았을 때 코드와 매우 유사하다고 생각했습니다. 어쨌든 신속하고 유익한 답변을 주셔서 감사합니다. – twenty49
확인. 대답이 도움이된다면 upvote 할 수 있습니다. 벡터를 사용하기 위해 포인터 코드를 바꾸는 것은 그리 좋지 않습니다. 언젠가는 실제 프로그램에서 그렇게해야 할 것입니다. – PaulMcKenzie