插入排序起始

Insertion Sort Initiation

本文关键字:插入排序      更新时间:2023-10-16

我是第一个遇到堆栈溢出的人,所以感谢大家耐心地帮助我解决这个问题。我正在用c++编写一个程序,通过对.txt文件中的数字进行排序来实现插入排序。它接受一个文件,显示其中的内容,然后询问用户是否要对数字进行排序。当我键入"y"时,它应该在我的代码中启动插入排序算法。但是现在它所做的就是完成编译。任何建议都非常感谢。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Read file input and display contents
ifstream& readfile(ifstream& file)
{
    string line;
    if (getline(file, line))
    {
        cout << line;
    }
    return file;
}
int main()
{
    string fileName, line, r;
    int n, i, j, k, temp;
    int a[n];
    ifstream fs;
    cout << "enter file: ";
    cin >> fileName;
    ifstream file(fileName);
    if (file.is_open())
    {
        while (readfile(file))
        {
        }
    }
    cout << endl << endl << "Sort File? y or n? ";
    cin >> r;
    if (r == "y")
    {
        for (i = 0; i < n; i++)
        {
            cin >> a[i];
        }
        for (i = 1; i < n; i++)
        {
            for (j = i; j >= 1; j--)
            {
                if (a[j] < a[j - 1])
                {
                    temp = a[j];
                    a[j] = a[j - 1];
                    a[j - 1] = temp;
                }
                else
                {
                    break;
                }
            }
        }
        for (k = 0; k < n; k++)
        {
            cout << a[k] << endl;
        }
    }
    else
    {
        cout << endl << "error" << endl;
    }
    cin.get();
    return 0;
}

n未初始化。

for (i=0;i<n;i++) 
{
  cin >> a[i];
}

这里什么都没有发生,因为(如果你幸运的话…)n=0。如果只需要5个条目,则将n初始化为5。

  • 使用STL容器,如std::vector,例如,你在这里使用类似C的语言…
  • 当用户初始化插入时,更改循环中的结束条件

例如,如果用户插入"stop"字:

std::vector<int> vIntegers; 
std::string input; 
int n = 0; 
while ( input != "stop") 
{ 
   std::cin >> input; 
   // test if integer here 
   { 
      vIntegers.push_back(n); 
   } 
}

在这里测试一个字符串是否是整数如何检查c++字符串是否为int类型?