冒泡排序示例

​​​​​​​

一、冒泡排序核心

void bbule_sort
{
int i = 0,j = 0;
int src[]={21,20,19,18,17,16,15,14};
int tmp = 0;
int length = 8;

for(i=0;i<length - 1;i++)
{
for(j=0;j<length-1;j++)
{
if(src[j]>src[j+1])     //将大的数往后挪
{
tmp = src[j];
src[j] = src[j+1];
src[j+1] = tmp;
}
}
}

}

二、冒泡排序可执行C程序

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int **bbule_point = NULL;

/* 冒泡排序子函数 */
int bbule_sort(int* src,int length)
{
int i=0;
int j=0;
int tmp=0;
int record_err = 0;
int* record_point = NULL;

if(NULL == src || 0 >= length)
{
printf("Func:%s Input Err:src=%d length=%d\n\r",src,length);
return -1;
}

/* 申请存放每次排序结果的数组的指针的数组空间 */
bbule_point = (int**)malloc(length*sizeof(int*));
if(NULL == bbule_sort)
{
printf("Func:%s Record Err,Malloc Failed!\n\r");
record_err = 1;
}
memset(bbule_point,0,sizeof(int*)*length);
record_point = malloc(length*sizeof(int));
if(NULL == record_point)
{
printf("Func:%s Record Err,Malloc Failed!\n\r");
}
else
{
memcpy(record_point,src,sizeof(int)*length);
bbule_point[0] = record_point;
}

/* 冒泡排序核心算法 */
for(i=0;i<length - 1;i++)
{
for(j=0;j<length-1;j++)
{
if(src[j]>src[j+1]) //将大的数往后挪
{
tmp = src[j];
src[j] = src[j+1];
src[j+1] = tmp;
}
}
/* 一趟排序完成,记录一下 */
if(!record_err)
{
record_point = (int*)malloc(sizeof(int)*length);
if(NULL == record_point)
{
printf("Func:%s Record Err,Malloc Failed!\n\r");
continue;
}
memcpy(record_point,src,sizeof(int)*length);
bbule_point[i+1]=record_point;
}
}

return 0;
}

void printf_str(int *src,int length)
{
int i=0;

if(NULL == src || 0 == length)
{
printf("Func:%s Input Err:src=%d length=%d\n\r",src,length);
return ;
}

printf("数组元素:");
for(i=0;i<length;i++)
{
printf("   %2d",src[i]);
}
printf("\n\r");
}

int main()
{
int src[]={92,80,77,72,64,53,42,30,29,21,12,2};
int i=0;

printf("******冒泡排序算法示例******\n初始");
printf_str(src,sizeof(src)/sizeof(int));
printf("共有%d个元素,开始排序\n",sizeof(src)/sizeof(int));
bbule_sort(src,sizeof(src)/sizeof(int));
printf("排序后");
printf_str(src,sizeof(src)/sizeof(int));
if(NULL == bbule_point)
{
printf("Err while Record Data!\n");
return -1;
}
printf("排序过程详解:\n");
printf("*原始数组*:");
printf_str(bbule_point[0],sizeof(src)/sizeof(int));
for(i=1;i < sizeof(src)/sizeof(int);i++)
{
printf("第%-2d次排序:",i);
printf_str(bbule_point[i],sizeof(src)/sizeof(int));
free(bbule_point[i]);
}

return 0;
}

三、冒泡排序结果及解析

3.1、第一组数据：完全降序的数组，将其排序为完全升序的数组

3.2、第二组数据：将乱序的数组排序为升序的数组