C # Implementation bubble sort to generic sort

Source: Internet
Author: User
Tags sorts

In the previous article, we talked about how C # implements bubble sorting. So did you ever think about how to do a bubble sort on any type of data? Here we will answer this question. First we learned that the essence of bubble sort is to rank an array of elements in ascending or descending order. Let's first take an example to feel the bubble sort, like an integral array that is sort of:

       <summary>  
       ///integer array bubble sort  
       ///</summary>  
       ///<param name= "arr" ></param>  
       public static void Bobblesort (int[] arr)  
       {for  
           (int i = 0; i < arr. Length-1; i++)  
           {for  
               (int j = 0; J < arr. Length-1-i; J + +)  
               {  
                   if (Arr[j] < Arr[j + 1])  
                   {  
                       int temp = arr[j];  
                       ARR[J] = arr[j + 1];  
                       Arr[j + 1] = temp;  
                   }}}  
         

The bubbling sort of the string array is:

        <summary>
        ///string array bubble sort
        ///</summary>
        ///<param name= "arr" ></param>
        public static void Bobblesortstr (string[] arr)
        {for
            (int i = 0; i < arr. Length-1; i++)
            {for
                (int j = 0; J < arr. Length-1-I; J + +)
                {
                    if (arr[j]. Length < Arr[j + 1]. Length)
                    {
                        String temp = Arr[j];
                        ARR[J] = arr[j + 1];
                        Arr[j + 1] = temp;
                    }}}
        

It is not hard to see through these two bubble sorts that the differences between the two sorts are only different when the conditions of the data exchange are judged, and the other places are the same. We might as well consider extracting this place to different conditions depending on the data. At this point we can consider writing this condition as a method to pass, give him a return value of the result is OK, then need to consider what type of return value. We observe the conditions that need to be compared to exchange the use of variables, since the consideration is the result of comparison, it is easy to think of the number of the relative size of three cases, greater than 0, less than 0, equal to 0. Here we put the equivalent of 0 into one of the cases. At this point the return value type is determined, we need to compare the method, smart if you think of the delegate can meet the needs here.

	

Then modify just the code:

        <summary>  
        ///Bubble sort  
        ///</summary>  
        ///<param name= "arr" ></param>  
        Public static void Bobblesort<t> (t[] arr,delcompare<t> del)  
        {for  
            (int i = 0; i < arr. Length-1; i++)  
            {for  
                (int j = 0; J < arr. Length-1-i; J + +)  
                {  
                    if (Del (Arr[j], arr[j + 1]) < 0)  
                    {  
                        T temp = arr[j];  
                        ARR[J] = arr[j + 1];  
                        Arr[j + 1] = temp;  
                    }}}  
          
You may also write a generic print of the printing method:
        <summary>  
        ///The elements of the print array  
        ///</summary>  
        ///<typeparam name= "T" ></typeparam>  
        ///<param name= "arr" ></param> public  
        static void Print<t> (t[] arr)  
        {for  
            (int i = 0; I < arr. Length; i++)  
            {  
                Console.Write (arr[i]+ "");  
            }  
            Console.WriteLine ();  
        

Well, let's test this at this point, and together we can witness the miracle:

        void Main (string[] args)  
        {  
            int[] nums = {1, 3, SI, 5, 6,, 6, 7, 8, 8, MB, 8, 9};  
            Print<int> (nums);  
            Bobblesort<int> (nums, (int t1, int t2) => {return  
                t1-t2;  
            });  
            Print<int> (nums);  
  
            Console.readkey ();  
        }  

The result is what we expected:


You don't think that's enough. So we might as well test, write a custom class like this:

    public class person
    {
        //Some properties public
        string Name {get; set;}
        public int Age {get; set;}
        public int Mathscore {get; set;}
        public int Chinesescore {get; set;}
        public int Englishscore {get; set;}
        Public person ()
        {

        } public person
        (string name, int age, int mathscore, int chinesescore, int englishscore) c12/>{this
            . name = name;
            This. Age = age;
            This. Mathscore = Mathscore;
            This. Chinesescore = Chinesescore;
            This. Englishscore = Englishscore;
        }
        public override string ToString ()
        {return
            string. Format (' {0} {1} {2} {3} {4} {5} ', this. Name, this. Age, this. Chinesescore, this. Mathscore, this. Englishscore, (this. Chinesescore + this. Mathscore + this. Englishscore));
        }
    


Then initializes an array of the person class:

            person[] PArr = new PERSON[10];
            Random range = new Random ();
            for (int i = 0; i < parr.length i++)
            {
                int rAge = range. Next (in);
                int rchinesescore = range. Next (0,);
                int rmathscore = range. Next (0,);
                int renglishscore = range. Next (0,);
                Parr[i] = new Person ("john _" + I, RAge, Rmathscore, Rchinesescore, renglishscore);
            

Test the results again (this time by total score):

            Print<person> (PARR);
            Bobblesort<person> (PARR, person P1, who P2) =>
            {return
                p1. Chinesescore + p1. Mathscore + p1. Englishscore-p2. Chinesescore-p2. Mathscore-p2. Englishscore;
            });
            Print<person> (PARR);

            Console.readkey ();

We were surprised to find that the results were still what we expected:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.