나는이 병합 정렬 기능을이 병합 정렬 함수가 왜 연결된 목록을 반환하는지 (C++)?
namespace sorted{
template<typename T>
class list {
/* other stuff */
list<T>* slice(int from, int to){
from = (from < 0) ? 0 : from;
to = (to > this->len) ? this->len : to;
list<T>* result = new list<T>();
node<T> *n = this->head;
int idx = 0;
while (n && (idx < this->len)){
if ((from <= idx) && (idx <= to)) result->append(n->value);
if (idx > to) break;
n = n->next;
idx++;
}
return result;
}
}
template<typename T>
list<T>* merge(list<T>* left, list<T>* right){
list<T>* result = new list<T>();
while ((left->length() > 0) || (right->length() > 0)){
if ((left->length() > 0) && (right->length() > 0)){
T l = left->get(0);
T r = right->get(0);
if (l <= r){
result->append(l);
left->remove(0);
} else{
result->append(r);
right->remove(0);
}
continue;
}
if (left->length() > 0) {
result->append(left->get(0));
left->remove(0);
}
if (right->length() > 0) {
result->append(right->get(0));
right->remove(0);
}
}
return result;
}
template<typename T>
list<T>* merge_sort(list<T>* original){
if (original->length() <= 1) {
return original;
}
int len = original->length();
list<T>* left = NULL;
list<T>* right = NULL;
if (len > 2){
left = original->slice(0,(len/2));
right = original->slice((len/2)+1,len-1);
}else if (len == 2){
left = original->slice(0,0);
right = original->slice(1,1);
}
left = merge_sort(left);
right = merge_sort(right);
delete original;
list<T>* result = merge(left, right);
delete left;
delete right;
return result;
}
/* other stuff */
}
을 가지고 그리고 여기
int main(int argc, char** argv){
sorted::list<int>* l = get_random_list();
l = merge_sort(l);
for (int i = 0; i < (l->length() - 1); i++){
int t = l->get(i);
int u = l->get(i+1);
if (t > u){
sorted::list<int>* m = l->slice(i - 5, i + 5);
cout << m << endl;
delete m;
break;
}
}
delete l;
return 0;
}
링크
내 질문 bitbucket.org project에이이이었다 내 주요 방법입니다했습니다.
슬라이싱 기능에서 목록이 제대로 반환되면 동일한 방식으로 수행되면 왜 주 기능으로 제대로 반환되지 않습니까?
[업데이트] 그들이 현재해야하는 방식대로 기능이 추가되었습니다. bitbucket에서 정식 버전이 나옵니다.
할당 담당자에게 문제가 있습니까? 너는 할당 연산자를 가지고 있지, 그렇지? –
병합은 어떻게 정렬됩니까? 당신은 단지 하나의 정렬되지 않은 슬라이스를 반환합니다 ... 당신은 당신의 결과물에있는 것이 아닙니다. – leftaroundabout
나는 그가 단순한 버전 –