文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>C#实现整数冒泡排序、选择排序

C#实现整数冒泡排序、选择排序

时间:2011-02-15  来源:zhouhb

        /// <summary>
        /// 交换两个整数的值
        /// </summary>
        /// <param name="aa">数1</param>
        /// <param name="bb">数2</param>
        private static void Swap(ref int aa,ref int bb)
        {
            int temp;
            temp = bb;
            bb = aa;
            aa = temp;
        }

   // 冒泡排序
   class Program
    {
        static void Main(string[] args)
        {
            int[] a={1,2,5,7,9,8,10,6,4,3};
            BubbleSort(a);
            for (int i = 0; i < a.Length; i++)
                Console.Write(a[i] + " ");
            Console.ReadKey();
        }
        /// <summary>
        /// 冒泡排序
        /// </summary>
        /// <param name="a">传入要排序的数组</param>
        private static void BubbleSort(int[] a)
        {
            for (int i = 0; i < a.Length - 1; i++)
            {
                for (int j = 0; j < a.Length - i - 1; j++)
                {
                    if (a[j] < a[j + 1])//降序排列
                    {
                        Swap(ref a[j], ref a[j + 1]);
                    }
                }
            }
        }
   }

 //选择排序
 class Program
 {
        static void Main(string[] args)
        {
            int[] a = { 1, 2,  4, 3,6,5,7,9,8 };
            SelectionSort(a);
            for (int i = 0; i < a.Length; i++)
                Console.Write(a[i] + " ");
            Console.ReadKey();
        }
        /// <summary>
        /// 选择排序
        /// </summary>
        /// <param name="a">传入要排序的数组</param>
        private static void SelectionSort(int[] a)
        {
            int k;
            for (int i = 0; i < a.Length - 1; i++)
            {
                k = i;
                for (int j = i+1; j < a.Length ; j++)
                {
                    if (a[j] < a[k])//升序排列
                    {
                        k = j;
                      
                    }
                }
                if(k!=i)
                    Swap(ref a[i], ref a[k]);
            }
        }
     }

相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载