zoukankan      html  css  js  c++  java
  • 基本排序算法之次序反转(Swap)操作

    Swap操作是我们在设计排序算法的时候很经常会用到的,例如比较两个值大小后,要对掉位置。我这篇日志是写出一个通用的方法来作处理。

    既然是值的位置对调,就要考虑到数据类型的问题。为了做到这个函数一次编写多次使用,我们使用了C# 2.0中的泛型技术,如下面代码示例

            static void Swap<T>(ref T value1, ref T value2)
            {
                T temp;
                temp = value1;
                value1 = value2;
                value2 = temp;
            }
     
    具体测试代码如下
        class Program
        {
            static void Main(string[] args)
            {
                int v1 = 2;
                int v2 = 3;
                Console.WriteLine("v1:{0},v2:{1}", v1, v2);
                Swap<int>(ref v1, ref v2);
                Console.WriteLine("v1:{0},v2:{1}", v1, v2);
    
                Customer c1 = new Customer(2);
                Customer c2 = new Customer(3);
                Console.WriteLine("c1:{0},c2:{1}", c1, c2);
                Swap<Customer>(ref c1, ref c2);
                Console.WriteLine("c1:{0},c2:{1}", c1, c2);
    
    
    
                Console.Read();
            }
    
            static void Swap<T>(ref T value1, ref T value2)
            {
                T temp;
                temp = value1;
                value1 = value2;
                value2 = temp;
            }
    
        }
    
        class Customer
        {
            public int CustomerID { get; set; }
            public Customer(int id) {
                CustomerID = id;
            }
    
            public override string ToString()
            {
                return string.Format("Customer {0}", CustomerID);
            }
        }
    测试的结果如下
    image 
    可以看到,我们已经实现了反转。至于该函数在排序算法中的具体应用,我们在具体的算法中会看到代码
  • 相关阅读:
    [转]Cordova + Ionic in Visual Studio
    [转]Getting Start With Node.JS Tools For Visual Studio
    TypeScript
    [转]NPOI TestFunctionRegistry.cs
    [转]Cordova android框架详解
    [转]POI : How to Create and Use User Defined Functions
    [转]用NPOI操作EXCEL--通过NPOI获得公式的返回值
    [转]Formatting the detail section to display multiple columns (水晶报表 rpt 一页多列)
    [转]Creating Mailing Labels in SQL Server Reporting Services (rdlc 数据1页 2竖排 显示)
    [转]Tetris(俄罗斯方块) in jQuery/JavaScript!
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1314858.html
Copyright © 2011-2022 走看看