快速排序功能不一致

Inconsistent Quick Sort Function

本文关键字:不一致 功能 快速排序      更新时间:2023-10-16

所以我写了这个快速排序函数,它适用于一些输入。例如,它适用于以下输入:"5 4 3 2 1","3 4 56 7"等。
但是,当我输入类似以下内容时:">0 3 5 4 -5 100 7777 2014",它总是会混淆多位数。
我希望有人可以帮助我指出我的代码在这个测试用例中失败的地方。

排序.cpp

std::vector<int> QuickSort::sortFunc(std::vector<int> vec, int left, int right) {
int i = left, j = right;
int tmp;
int pivot = vec.at( (left + right) / 2 );
/* partition */
while (i <= j) { 
    while (vec.at(i) < pivot)
        i++;
    while (vec.at(j) > pivot)
        j--;
    if (i <= j) {
        tmp = vec.at(i);
        vec.at(i) = vec.at(j);
        vec.at(j) = tmp;
        i++;
        j--;
    }
}
/* recursion */
if (left < j)
    return sortFunc( vec, left, j );
if (i < right)
    return sortFunc( vec, i, right );
else
{
    return vec;
}
}

主.cpp

 int main()
{
// The user inputs a string of numbers (e.g. "6 4 -2 88 ..etc") and those integers are then put into a vector named 'vec'.
std::vector<int> vec;
// Converts string from input into integer values, and then pushes said values into vector.
std::string line;
if ( getline(std::cin, line) )
{
    std::istringstream str(line);
    int value;
    str >> value;
    vec.push_back( value );
    while ( str >> value ) 
    {
        vec.push_back( value );
    }
}
// Creating QuickSort object.
QuickSort qSort;
QuickSort *ptrQSort = &qSort;
// Creating new vector that has been 'Quick Sorted'.
int vecSize = vec.size();
std::vector<int> qSortedVec;
qSortedVec = ptrQSort->sortFunc( vec, 0, vecSize-1 );
// Middle, start, and end positions on the vector.
int mid = ( 0 + (vec.size()-1) )  / 2;
int start = 0, end = vec.size() - 1;
// Creating RecursiveBinarySearch object.
RecursiveBinarySearch bSearch;
RecursiveBinarySearch *ptrBSearch = &bSearch;
//bool bS = ptrBSearch->binarySearch( qSortedVec, mid, start, end );
bool bS = ptrBSearch->binarySearch( bSortedVec, mid, start, end );

/*--------------------------------------OUTPUT-----------------------------------------------------------------------*/
// Print out inputted integers and the binary search result.
// Depending on the binary search, print either 'true' or 'false'.
if ( bS == 1 )
{
    std::cout << "true ";
}
if ( bS == 0 )
{
    std::cout << "false ";
}
// Prints the result of the 'quick sorted' array.
int sortedSize = qSortedVec.size();
for ( int i = 0; i < sortedSize; i++ )
{
    std::cout << qSortedVec[i] << " ";
}
std::cout << "n";

return 0;
}

感谢您能给我的任何帮助。

我不确定这是否完全解决了它,但是在对左侧部分进行排序后,您仍然需要对右侧部分进行排序,但您已经返回了。

此外,按值传递向量并返回它是开销,并且不需要,因为最终应该只有一个版本的向量,因此最好通过引用传递。 在执行递归时,有时需要按值传递并返回,尤其是在回溯(寻找不同的路径(时,但在这种情况下,左和右提供所需的状态时不需要。