冒泡排序simple sorting algorithm for bubble sort

simple sorting algorithm for bubble sort
冒泡排序来源于生活经验,它是指每次从要排序的N个元素中查找出数值最大或者最小的元素,依次排列。因为每次查找都得与剩下的每一个元素进行大小比较,所以其算法复杂度高。达到O(n²)。

#include "stdio.h"

typedef  unsigned char uint8_t;

void compare_switch(uint8_t* a, uint8_t* b) // point parameter
{
    if (*a > *b)
    {
      uint8_t temp = *a;
       *a = *b;
       *b= temp;
    }
}

void bubble_sort(uint8_t* array, uint8_t len)
{
   uint8_t i;
// This won't give you the correct length of the array when passed to a function because sizeof(array) returns the size of the pointer, not the size of the array.
// len = sizeof(array)/sizeof(array[0]); 

   for (i = 0; i < (len -1); i++)        // len -1 cycle
   {
      for(uint8_t j = 0; j < (len - i - 1); j++) // 0-- len-i-1 cycle
      {
         compare_switch(&array[j], &array[j+1]);
      }
// print the array each sort.
      printf("%d cycle :", i);

      for (uint8_t k = 0; k < (len -1); k++)        // len -1 cycle
      {
         printf("%d, ", array[k]);
      }

      printf("\n");
// 
   }
}

void main(void)
{
    uint8_t array[] = {200,34,1,10,5,28,13,22,69,7};

    uint8_t len = sizeof(array)/sizeof(array[0]);  // array number

    bubble_sort(array, len);

   printf("the array after sorted:\n");
   for (uint8_t k = 0; k < (len); k++)        // len -1 cycle
   {
       printf("%d, ", array[k]);
   }
}

// result:
// PS E:\006-Programing\007-c> gcc -o main  main.c
// PS E:\006-Programing\007-c> ./main
// 0 cycle :34, 1, 10, 5, 28, 13, 22, 69, 7, 
// 1 cycle :1, 10, 5, 28, 13, 22, 34, 7, 69, 
// 2 cycle :1, 5, 10, 13, 22, 28, 7, 34, 69, 
// 3 cycle :1, 5, 10, 13, 22, 7, 28, 34, 69, 
// 4 cycle :1, 5, 10, 13, 7, 22, 28, 34, 69, 
// 5 cycle :1, 5, 10, 7, 13, 22, 28, 34, 69, 
// 6 cycle :1, 5, 7, 10, 13, 22, 28, 34, 69, 
// 7 cycle :1, 5, 7, 10, 13, 22, 28, 34, 69, 
// 8 cycle :1, 5, 7, 10, 13, 22, 28, 34, 69, 
// the array after sorted:
// 1, 5, 7, 10, 13, 22, 28, 34, 69, 200,
// PS E:\006-Programing\007-c>
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值