快速排序不对 C++ 进行排序
quicksort not sorting c++
我正在尝试编写一个快速排序函数来对 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;
}
这一行看起来不合适:
int pivot=numbers.size()/2;
您正在为枢轴选择numbers
矢量的中间元素,而不考虑start
和end
位置。
除其他事项外,当您移动索引以查找交换时,您实际上并没有查看向量的内容。 本节:
while( i < pivot && i < j)
i++;
while( j >= pivot && i < j)
j--;
应该改成这样:
while( numbers[i] < pivot && i < j)
i++;
while( numbers[j] >= pivot && i < j)
j--;
正如其中一位评论者所提到的,更大的教训是学习使用一个好的调试器来单步执行代码。
同样,您应该选择透视作为数组值。 例如 pivot = numbers[start]
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序