排序算法——冒泡排序

一、介绍:

冒泡排序原理就是从第一个元素开始,比较其后边的一个元素的大小,按照排序方式进行交换位置,直到将所有元素的顺序排列好为止。演示如下:

视频演示:

冒泡排序演示_网络游戏热门视频 (bilibili.com)https://www.bilibili.com/video/BV1EZ4y1o7cF/?spm_id_from=333.999.0.0&vd_source=bf6b294c298d9c158ee178418c8d651a

二、运行代码:

cs 复制代码
   void BubblingSort(int[] data)
   {
       //首先是排序 data.length -1 轮
       for (int i = data.Length - 1; i > 0; i--)
       {
           //每轮比较j次
           for (int j = 0; j < i; j++)
           {
               //从小到大排序
               if (data[j] > data[j + 1])
               {
                   int temp = data[j];
                   data[j] = data[j + 1];
                   data[j + 1] = temp;
               }
           }
       }
   }

   void BubblingSort2(int[] data)
   {
       for (int i = 0; i < data.Length; i++)
       {
           for (int j = 0; j < data.Length - 1 - i; j++)
           {
               //从小到大排序
               if (data[j] > data[j + 1])
               {
                   int temp = data[j];
                   data[j] = data[j + 1];
                   data[j + 1] = temp;
               }
           }
       }
   }

优化代码:

检测到数据后边的数据都已排好序则停止排序

cs 复制代码
  void OptimizeBubblingSort(int[] data)
  {
      int times = 0 ,flag = 0 ;
      //首先是排序 data.length -1 轮
      for (int i = data.Length - 1; i > 0; i--)
      {
          flag = 0;
          //每轮比较j次
          for (int j = 0; j < i; j++)
          {
              //从小到大排序
              if (data[j] > data[j + 1])
              {
                  int temp = data[j];
                  data[j] = data[j + 1];
                  data[j + 1] = temp;
                  flag++;
              }
              times++;
          }
          if (flag == 0)
          {
              Debug.Log(times);
              return;
          }
      }
      Debug.Log(times);
  }
相关推荐
DoraBigHead25 分钟前
小哆啦解题记——映射的背叛
算法
Heartoxx36 分钟前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior1 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者1 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7892 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价2 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七2 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode
凌肖战3 小时前
力扣网编程274题:H指数之普通解法(中等)
算法·leetcode
秋说3 小时前
【PTA数据结构 | C语言版】将数组中元素反转存放
c语言·数据结构·算法
WebInfra3 小时前
如何在程序中嵌入有大量字符串的 HashMap
算法·设计模式·架构