从文件中读数到数组,且用于冒泡排序

时间:2022-12-29 20:51:59

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;

//冒泡排序算法
namespace BubbleSort
{
    public class BubbleSort
    {
        public void Sort(int[] list)
        {
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < list.Length) && (!done))
            {
                done = true;
                {
                    for (i = 0; i < list.Length - j; i++)
                    {
                        if (list[i] > list[i + 1])
                        {
                            done = false;
                            temp = list[i];
                            list[i] = list[i + 1];
                            list[i + 1] = temp;
                        }
                    }
                    j++;
                }
            }
        }
    }
    public class MainClass
    {
        public static void Main()
        {
            //从文件中读取数字到数组中
            StreamReader objReader = new StreamReader(@"D:\Sample apps\C#Algrorithm\number.txt");
            string sLine = "";
            ArrayList LineList = new ArrayList();

            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null && !sLine.Equals(""))
                   LineList.Add(sLine);
            }
            //object类型的Linelist转化为int类型的数组

            //关于这一段程序,我尝试过于用int[] ints = (int[])LineList.ToArray(typeof(int));,但失败了,还望高手可以指点指点,不胜感激!
            int[] ints = new int[LineList.Count];
            int i = 0;
            foreach (Object obj in LineList)
            {
                ints[i] = Convert.ToInt32(obj);
                i++;
            }

            //对数组中的数字排序
            BubbleSort bs = new BubbleSort();
            bs.Sort(ints);
            for (int m = 0; m < ints.Length; m++)
            {
                Console.Write(" {0}", ints[m]);
            }
            Console.WriteLine();
        }
    }
}
文件中的数字为:

1
2
3
6
549
59
4
56
92
19
40
2

 

运行结果为:

 1 2 2 3 4 6 19 40 56 59 92 549
Press any key to continue . . .