그래서 벡터에서 중간 값을 찾기 위해 C++에서 quickselect 알고리즘을 구현하려하지만 목록을 부분적으로 정렬하지 않고 반환하지도 않습니다 올바른 중앙값.내 quickselect 알고리즘이 올바른 값을 반환하지 않습니다
오류가있는 곳을 찾을 수 없습니다. 나는이 알고리즘을 처음 사용하기 때문에 구현하기 처음이다. 아래에 제 코드를 포함 시켰습니다. 그래서 나보다 더 잘 알고있는 사람이 무엇이 잘못되었는지에 대해 알고 있다면, 여러분의 의견을 진심으로 감사드립니다.
//Returns the index of the object with the kth largest value
int QuickSelect(vector<Object *> & list, int left, int right, int k){
/*-Base case-*/
if(left == right) /*List only contains a single element*/
return left; /*Return that index*/
int pivotIndex = left + (rand() % (int)(right - left + 1));
int pivotNewIndex = Partition(list, level, left, right, pivotIndex);
int pivotDist = pivotNewIndex - left + 1;
if(pivotDist == k)
return pivotNewIndex;
else if (k < pivotDist)
return QuickSelect(list, level, left, pivotNewIndex-1, k);
else
return QuickSelect(list, level, pivotNewIndex+1, right, k-pivotDist);
}
int Partition(vector<Object *> & list, int left, int right, int pivotIndex){
int pivotValue = list.at(pivotIndex)->value;
std::swap(list[pivotIndex], list[right]);
int storeIndex = left;
for(int i = left; i < right; i++){
if(list.at(i)->value < pivotValue){
std::swap(list[storeIndex], list[i]);
storeIndex++;
}
}
std::swap(list[right], list[storeIndex]);
return storeIndex;
}
표준을 사용할 수 없습니까? http://en.cppreference.com/w/cpp/algorithm/nth_element –
이론적으로는 그렇습니다.하지만 직접 구현하여 알고리즘에 대한 이해를 얻으려고합니다 ...하지만 현재 붙어있어 도움이 필요합니다. – user1782677
'QuickSelect'는 선언되지 않은 변수 인'level'을 가지고'Partition'을 호출합니다. 컴파일되지 않으면 디버그하기가 어렵습니다. –