ds冒泡排序

#include<stdio.h>
#include<stdlib.h>
#define maxn 10 //冒泡排序 从小到大
/* 测试数据
9
5 7 8 7 0 2 1 6 9
*/
typedef struct LNode *List;
struct LNode{
    int Data[maxn];
    int Last;//线性表最后一个元素的位置
};
List MakeEmpty();
void Insert(List L, int x, int n);
void BubbleSort(List L);
void print(List L);
int N; //要排序的数字的个
int flag; //标记某一趟是否发生交换
int main(){
    int x;
    List L = MakeEmpty();
    scanf("%d", &N); //元素个数
    while(N--){ //插入元素
        scanf("%d", &x);
        Insert(L, x, L->Last+1);
    }
    //print(L);
    BubbleSort(L);
    print(L);
    return 0;
}
List MakeEmpty(){
    List p;
    p = (List)malloc(sizeof(struct LNode));
    p->Last = 0;
    return p;
}
void Insert(List L, int x, int n){ // 插入的表 元素 位置
    for(int i = L->Last+1; i > n; i--){
        L->Data[i] = L->Data[i-1];
    }
    L->Data[n] = x;
    L->Last++;
}
void BubbleSort(List L){
    int m = L->Last - 1; //每一趟冒泡一个,还剩最后一趟的时候,只剩一个泡要排了,所以不用排序了
    flag = 1;
    while(m && flag){
        flag = 0; //若本趟没有发生交换,break 结束排序
        for(int j = 1; j <= m; j++){
            if(L->Data[j] > L->Data[j + 1]){
                //运用"异或运算"而不需要临时变量交换两个变量的值
                L->Data[j]^=L->Data[j+1]^=L->Data[j]^=L->Data[j+1];
                flag = 1;
            }
        }
        m--;
    }
}
void print(List L){
    for(int i = 1; i <= L->Last; i++){
        printf("%d ", L->Data[i]);
    }
    printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值