You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文本文件数字传入数组并使用BubbleSort排序(C#)

解决BubbleSort排序文本文件数字的问题

你已经成功读取了文本文件中的数字,但目前仍在使用示例固定数组执行排序。只需把解析后的数字转换为int数组,替换掉固定数组即可,具体改法如下:

关键修改点

  • 无需使用LinkedList<int>,直接将解析后的字符串数组转为int数组更高效
  • 删除固定数组定义,把从文件读取到的字符串数字转为int数组
  • 用新数组调用BubbleSort方法并输出排序结果

修改后的完整代码

using System;
using System.IO;
using System.Diagnostics;

public class Trial
{
    public static void Main(string[] args)
    {
        Stopwatch stopwatch = new Stopwatch();

        // 获取文件路径
        string currentDirectory = Directory.GetCurrentDirectory();
        string filePath = Path.Combine(currentDirectory, "a2_task1_input1.txt");
        Console.WriteLine(filePath);

        // 读取文件内容
        string fileContents = File.ReadAllText(filePath);
        Console.WriteLine(fileContents);

        stopwatch.Start();

        // 分割字符串并转换为int数组
        string[] numberStrings = fileContents.Split(new char[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        int[] array = new int[numberStrings.Length];
        for (int i = 0; i < numberStrings.Length; i++)
        {
            array[i] = int.Parse(numberStrings[i]);
        }

        // 执行排序并输出结果
        BubbleSort(array);
        foreach (int number in array)
        {
            Console.Write(number + " ");
        }

        stopwatch.Stop();
        long elapsedTimeMs = stopwatch.ElapsedMilliseconds;
        Console.WriteLine("\nElapsed time: " + elapsedTimeMs);
    }

    static void BubbleSort(int[] arr)
    {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    // 交换元素
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

改动说明

  1. 移除了LinkedList<int>的冗余使用,直接创建对应长度的int数组,循环将字符串数字解析存入数组
  2. 删除了原固定数组int[] array = { 2, 4, 1, 3, 8, 6, 9, 7, 5 };,替换为从文件解析得到的数组
  3. 保持BubbleSort方法逻辑不变,直接传入新数组即可完成文件数字的排序

运行修改后的代码,控制台将输出文本文件中数字的排序结果,而非原示例数组的结果。

内容的提问来源于stack exchange,提问作者Jackson Chapman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:43:21