C#--基於delegate實現不同功能的排序

iamzxf發表於2015-03-30


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace delegateDemo
{
    public delegate bool comparison(int x, int y);

    class BubbleSorter
    {
        public static void sort(int[] nArray, comparison comp)
        {
            for (int i = 0; i < nArray.Length; i++)
            {
                for (int j = i + 1; j < nArray.Length; j++)
                {
                    if (comp(nArray[i], nArray[j]))
                    { 
                        int temp=nArray[i];
                        nArray[i]=nArray[j];
                        nArray[j]=temp;
                    }
                }
            }
        }

        public static bool CompareValueDecend(int x, int y)
        { return x > y; }
        public static bool CompareAbsAscend(int x, int y)
        { return Math.Abs(x) < Math.Abs(y); }
        public static bool CompareString(int x, int y)
        {
            return string.Compare(x.ToString().Trim(),y.ToString().Trim())<0;
        }

    }
    
    class Program
    {
        static void Main(string[] args)
        {
            int i;
            int[] items = { 5, -6, 34, 123, -45 };

            BubbleSorter.sort(items, BubbleSorter.CompareAbsAscend);
            foreach (int tt in items)
                Console.Write("{0,5}",tt);
            Console.WriteLine();

            BubbleSorter.sort(items, BubbleSorter.CompareValueDecend);
            foreach (int tt in items)
                Console.Write("{0,5}", tt);
            Console.WriteLine();

            BubbleSorter.sort(items, BubbleSorter.CompareString);
            foreach (int tt in items)
                Console.Write("{0,5}", tt);
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}




相關文章