算法整理(1)——冒泡排序

1、冒泡排序

(1)算法原理:

  1.比较相邻元素,如果第一个比第二个大,就交换他们两个;

  2.对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数;

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

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

 (2)源码

  1.C#

 1 public static void funBubblesort(int[] array)
 2         {
 3             for (int i = 0; i < array.Length - 1; i++)
 4             {
 5                 Boolean flag = true;
 6                 for (int j = 0; j < array.Length - 1 - i; j++)
 7                 {
 8                     flag = false;
 9                     if (array[j] > array[j + 1])
10                     {
11                         int temp = array[j];
12                         array[j] = array[j + 1];
13                         array[j + 1] = temp;
14                         flag = true;
15                     }
16                 }
17             }
18         }

   2.C 

 1 void Bubble_Sort_data(uint16_t *dataptr,uint8_t len)
 2 {
 3     uint16_t      temp=0;
 4     uint8_t    i,j;
 5     for(i=0;i<len-1;i++)
 6     {
 7         for(j=i+1;j<len;j++)
 8         {
 9             if(dataptr[i]>dataptr[j])
10             {
11                 temp = dataptr[i];
12                 dataptr[i] = dataptr[j];
13                 dataptr[j] = temp;
14             }
15         }
16     }
17 }

   (3)求平均值

 1 uint16_t Compute_average(uint16_t *dataptr,uint8_t len,uint8_t abn)
 2 {
 3     uint8_t    i=0;
 4     uint32_t     temp=0;
 5     for(i=abn;i<=len-abn-1;i++)
 6     {
 7         temp += dataptr[i];        
 8     }
 9     temp /= (len-2abn);
10     
11     return((uint16_t)temp);
12 }

猜你喜欢

转载自www.cnblogs.com/forgivenesstomhwl/p/12357753.html
今日推荐