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

3 篇文章 0 订阅

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 . . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值