为什么我的程序在选择排序函数后暂停

Why is my program pausing after a selection sort function?

本文关键字:函数 暂停 排序 选择 我的 程序 为什么      更新时间:2023-10-16

我有一个简单的排序程序正在由 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'的值。只需使用向量的大小初始化它即可。

正如其他人评论的那样,整个工作正在进行中。