我正在尝试编写一个快速排序函数来对 10 到 1,000,000 个数字之间的任何地方进行排序。它遍历所有内容但不排序,只是按原样打印向量。
while
由于某种原因,它过早地跳出了循环。我正在使用的测试输入是:(3 6 2 5 1 7 9 10 4 8)。它的输出: (1 2 6 5 3 7 9 10 4 8)
int main()
{
std::cout << "Which file would you like to sort?\n";
std::cin >> file;
std::ifstream in(file.c_str());
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
int max = numbers.size();
quickSort(numbers, 0, max-1);
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
return 0;
}
void quickSort(vector<int> &numbers, int start, int end)
{
int i = start;
int j = end;
int pivot=numbers[start];
int temp;
while( i != j )
{
while( numbers[i] < pivot && i < j)
i++;
while( numbers[j] >= pivot && i < j)
j--;
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
if( j < start )
{
quickSort( numbers, start, j );
}
if( i < start )
{
quickSort( numbers, i, end);
}
}
return;
}