zoukankan      html  css  js  c++  java
  • C#实现整数冒泡排序、选择排序

            首先定义排序过程中要用到的Swap方法,用于交换两个整数的值:

            /// <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]);
                }
            }
         }

  • 相关阅读:
    开发者最好的推广平台
    [ERR] 2006
    PS通道
    PS图层样式
    PS 图层 蒙版
    科研狗的基本绘图技巧 | PS | AI
    memcached的常规操作:增删改查【转】
    mysql:pt-online-schema-change 在线修改表、删除表数据【转】
    HAProxy的四层与七层的区别及透传IP实战案例【转】
    【springBoot】SpringBoot修改启动logo图案
  • 原文地址:https://www.cnblogs.com/zhouhb/p/1955280.html
Copyright © 2011-2022 走看看