为什么我的程序在选择排序函数后暂停
Why is my program pausing after a selection sort function?
我有一个简单的排序程序正在由 Dev-C++ 4.9.8.0 编译。我运行了该程序(是的,这编译了),它只是在显示首次显示向量的行后停止。注意 - 它不会冻结,它似乎只是暂停一下。在代码中,选择排序接下来是,所以我假设错误发生在那里,但没有错误消息让我甚至弄清楚该怎么做!
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>
#include <ctime>
using namespace std;
void bubbleSort (vector<int>& data)
{
if(data.size() <= 1)
return;
int flag=1;
int temp;
for(int i=1; (i<=data.size()) && flag; i++)
{
flag=0;
for(int j=0; (j<data.size()-1); j++)
{
if(data[j+1] > data[j])
{
temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
flag=1;
}
}
}
}
void selectionSort(vector<int>& data)
{
int min, temp, n=data.size();
for (int i=0; i<n; i++)
{
min = i;
for (int j=i+1; j<n; j++)
{
if (j<min)
{
temp=i;
i=min;
min=temp;
}
}
}
}
int main()
{
int n;
vector<int> data;
cout<<"Vector length?: "<<endl;
cin>>n;
srand(time(0));
for (int i=0; i<n; i++)
{
data.push_back(rand()%20+1);
}
cout<<"Vector: ";
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<", ";
}
selectionSort(data);
cout<<"Sorted Vector: ";
for (int i=0; i<data.size(); i++)
{
cout<<data[i]<<", ";
}
system("Pause");
return 0;
}
selectionSort() 方法具有变量 'n',它完全是一个随机值,恰好在该位置的堆栈上。您尚未初始化它!
你有一个嵌套循环,它是 O(n^2)。假设 n 是 1982734 或一些这样的任意大数字。你只是在循环1982734 * 1982734次。最终它将完成。你为什么不在selectionSort()中打印'n'的值。只需使用向量的大小初始化它即可。
正如其他人评论的那样,整个工作正在进行中。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 如何在不接触函数本身的情况下暂停和恢复 C++11 std::thread 的功能
- 如何在函数中暂停程序,直到用户在窗体上执行某些操作
- 暂停并恢复c++函数
- 为什么我的程序在选择排序函数后暂停
- Visual C++ 是否需要在'main'函数结束之前暂停应用程序
- 暂停 std::thread,直到函数完成
- 我的C++代码关于"if和if else"函数和"暂停"有什么问题?
- 使用 <Windows.h> 暂停时间并继续执行其他功能的函数
- c++暂停函数似乎不能在do-while循环中工作