冒泡与文件排序

时间:2014-03-08 02:46:07

标签: c# bubble-sort

好的,请原谅我非常粗略的代码,但是这个项目是在急速(和轻微的刺激)。我要在1-40之间排序20个数字,但我不能使用任何数据容器(数组等),我也不能为每个数字使用变量。我想出了将20个文件用作单个阵列的想法。我正在尝试实现冒泡排序(仓促选择)来对文件中的数据进行排序。问题是,我没有太多的经验写入文件,所以它成为一个非常非常大的头痛。

for (int i = 0; i <20; i++) // assign smallest
{
   for (int j = 1; j <= 19; j++ ) // find the smallest
   {

      filename = "" + j.ToString() + ".txt";          // _.txt assigned to filename
      file = File.OpenText("" + filename);            //file assigned path of _.txt
      a = Int32.Parse(file.ReadLine());               //pull number from file 1, assign to a
      file.Close();
      filename1 = "" + (j + 1).ToString() + ".txt";   // _+1.text assigned to filename1
      file1 = File.OpenText( filename1);              //   file1 assigned path of _+1.txt
      b = Int32.Parse(file1.ReadLine());              // pull number from file 2, assign to b

      file1.Close();


      if (a > b) //bubble sort
      {
          temp = a;  // assign temp to a

          Sorting = File.CreateText( filename);
          Sorting.Write(b);

          Sorting = File.CreateText( filename1);
          Sorting.Write(temp);

          Sorting.Close();

      }
   }
}

这里有一个逻辑错误,就是把我抛弃,最后在外部for循环运行一次之后它说“无法打开2.txt”。尽管我确定每次迭代都会关闭文件流,但它告诉我这个。任何见解都将非常感激。

0 个答案:

没有答案