您的位置:首页 > 编程语言 > C#

C# 冒泡排序法示例代码(包含泛型方法)

2007-05-31 14:55 351 查看
using System;
using System.Collections.Generic;
using System.Text;

namespace bleb_sort
{
    class Program
    {
        public class SwapObj
        {
            public static void swap<T>(ref T a, ref T b)
            {
                T c;
                c=a;
                a=b;
                b=c;
            }
        }

        static void Main(string[] args)
        {
            //冒泡排序:
            int[] num = new int[] { 12, 3, 6, 16, 19, 7, 33, 21, 20, 100, 100, 115, 55, 58, 77};

            foreach (int i in num)
            {
                Console.Write(i.ToString() + ", ");
            }

            Console.WriteLine();
            Console.WriteLine("排序后:");

            int counter1 = 0;
            int counter2 = 0;
            for(int i=0; i<num.Length-1;i++)
            {
                for(int j=i+1; j<num.Length; j++)
                {
                    if(num[i]<num[j])
                    {
                        SwapObj.swap<int>(ref num[i], ref num[j]);
                        counter1++;
                    }
                    counter2++;
                }
            }

            Console.WriteLine( "循环了{0}次。", counter2);
            Console.WriteLine("其中交换了{0}次。", counter1);
            foreach (int i in num)
            {
                Console.Write(i.ToString() + ", ");
            }

            Console.ReadLine();
        }
    }
}

电脑学习网 - http://www.why100000.com
  张庆, 2007.5.31
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# class system string c
相关文章推荐