zoukankan      html  css  js  c++  java
  • C#学习笔记(27)——委托排序(1)

    说明(2017-11-20 17:21:35):

    1. 感觉难点都在冒泡排序上。。貌似之前跳过去了没学啊!冒泡排序的精髓就在于,两两比较,最大的排到最后一位,再把前面的重新两两比较,把最大的排到倒数第二位,一直排完,最小的就在第一位了。

    2. 两个排序方法,自己写的numCompare按数字大小排序,和系统自带的string.Compare按字符大小排序,分别授权给委托,哪个授权执行哪个方法。

    3. 后面说要搞得再复杂一点,所以待续。。To be continued。。

    4. 忘了写,效果要在Console.ReadKey()那一行加断点,观察nums的值得排序。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace _04_委托排序
    {
        class Program
        {
            public delegate int MyDel(string s1, string s2);
            static void Main(string[] args)
            {
                string[] nums = "600,1,10,100,22,200,3,130,8".Split(',');
                //定义委托变量
                MyDel myDel;
                //选择一个方法授权,字符串排序,或者数字排序
                //string.Compare()字符串排序,应该是按照ASCII码排序。
                myDel = string.Compare;
                //myDel = numCompare;
                for (int i = 0; i < nums.Length; i++)
                {
                    for (int j = 0; j < nums.Length - i - 1; j++)
                    {
                        if (myDel(nums[j], nums[j + 1]) > 0)
                        {
                            string a = nums[j];
                            nums[j] = nums[j + 1];
                            nums[j + 1] = a;
                        }
                    }
                }
                Console.ReadKey();
            }
            //按照数字大小排序
            public static int numCompare(string n1, string n2)
            {
                int num1 = Convert.ToInt32(n1);
                int num2 = Convert.ToInt32(n2);
                if (num1 < num2)
                {
                    return -1;
                }
                else if (num1 > num2)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
        }
    }

     另外,numCompare方法可以简写,后来回看视频才发现的:

            public static int numCompare(string n1, string n2)
            {
                return Convert.ToInt32(n1) - Convert.ToInt32(n2);
            }
  • 相关阅读:
    HDU 5044 Tree 树链剖分
    HDU 3966 Aragorn's Story 动态树 树链剖分
    HDU 2475 BOX 动态树 Link-Cut Tree
    上阶段总结
    HDU 3487 Play with Chain | Splay
    HDU 3726 Graph and Queries 平衡树+前向星+并查集+离线操作+逆向思维 数据结构大综合题
    VIJOS P1081 野生动物园 SBT、划分树模板
    VIJOS P1647 不差钱 SBT
    HDU 1890 Robotic Sort | Splay
    基础练习(VIP部分-持续更新)
  • 原文地址:https://www.cnblogs.com/Jacklovely/p/7867362.html
Copyright © 2011-2022 走看看