【排序】BubbleSort

本文解释了冒泡排序名称的由来及其工作原理。通过从数组底部开始比较并逐步将较大的元素向上移动,每次循环都能找到当前未排序部分的最小元素。文章还提供了实现冒泡排序的 C 语言代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Why it call Bubble Sort? It's name contains what kind of method it uses:

Every time by comparing i_item  from  bottom to top ,if found greater one, i_item raises one step .

In one loop, one smallest one is found.

Here are the codes:

 

// BubbleSort.c
#include <stdio.h>
#include  " type.h "
void swap(ElemType  **a, ElemType **b)
{

    ElemType tmp = *a;
    *a=*b;
    *b=tmp;

}
void BubbleSort( SqList *L)
{
     int i;
     for(i= 0;i<L->length ; i++)
    {
         int j;
         for(j=i+ 1; j<L->length; j++)
        {
             if(L->data[i]> L->data[j])
            {
                swap(&L->data[i], &L->data[j]);
            }
        }
    }
}
void printContent(SqList *L)
{
     int i;
     for(i= 0;i< L->length;i++)
    {
        printf( " %d  ", L->data[i]);
    }
}
void main( void)
{
    SqList list, *slist;
    slist = &list;
    slist->data[ 0]= 1;
    slist->data[ 1]= 5;
    slist->data[ 2]= 4;
    slist->data[ 3]= 2;
    slist->data[ 4]= 22;
    slist->length= 5;
    printContent(slist);
    printf( " \n ");
    BubbleSort(slist);
    printContent(slist);
    printf( " \n ");
}
There will be one blog later about swap function to explain the pointer problem

 

// type.h
#define MAXSIZE 20
typedef  int ElemType;
typedef  struct {
    ElemType data[MAXSIZE];
     int length;
}SqList;

 

转载于:https://www.cnblogs.com/no7dw/archive/2012/11/17/2774256.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值