zoukankan      html  css  js  c++  java
  • C#算法之冒泡排序

    排序规则:

      比较相邻的元素。如果第一个比第二个大,就交换它们两个。

      对每对相邻元素做同样的工作,从开始第一对到最后一对。这步做完之后,最后的元素会是最大的数。

      针对所有的元素重复以上的步骤,除了最后一个。

      持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要进行比较。

    时间复杂度:

      平均时间复杂度:O(n^2) 最好情况O(n),最坏情况 O(n^2)

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace 排序算法
    {
        class BubbleSort
        {
            public static void Sort(int[] arr)
            {
                int n = arr.Length;
                for(int i = 0; i < n; i++)
                {
                    // 减去i不需要对已经排好的元素再次进行比较
                    for (int j = 0; j < n -1 - i; j++)
                    {
                        if (arr[j] > arr[j + 1])
                        {
                            Swap(arr, j, j + 1);
                        }
                    }
                }
            }
            private static void Swap(int[] arr, int i,int j)
            {
                int t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
            }
        }
    }

    泛型冒泡排序

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace 排序算法
    {
        class BubbleSortGeneric
        {
            public static void Sort<E>(E[] arr) where E : IComparable<E>
            {
                int n = arr.Length;
                for(int i = 0; i < n; i++)
                {
                    for(int j = 0; j < n - 1 - i; j++)
                    {
                         if( arr[j].CompareTo(arr[j + 1]) > 0)
                        {
                            Swap(arr, j, j + 1);
                        }
                    }
                }
            }
    
            private static void Swap<E> (E[] arr, int i, int j)
            {
                E t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
            }
        }
    }
  • 相关阅读:
    mysql外键添加error1215
    shell命令获取最新文件的名称
    centos7 apache提供文件下载
    centos7 时间设置
    微服务通信的类型
    angular-cli
    npm
    模块相关
    加油!冲冲冲
    软件评测
  • 原文地址:https://www.cnblogs.com/sy-liu/p/13262498.html
Copyright © 2011-2022 走看看