【汇编语言实战】冒泡排序

C语言描述:

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    for (i = 0; i < n - 1; i++) {
        // 每次循环将当前最大的数移动到末尾
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // 交换 arr[j] 和 arr[j + 1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {7, 6, 9, 5, 3, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    // 调用冒泡排序函数
    bubbleSort(arr, n);

    printf("排序后的数组: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");

    return 0;
}

汇编语言:

INCLUDE Irvine32.inc
.data
    arr dd 52, 13, 31, 35, 212, 828, 65, 68, 78 ;定义数组
    len dd ($-arr)/4 ;定义数组的长度变量
.code
main PROC
    mov edx,offset arr ;edx用于存储数组首元素的地址
    mov ecx,len ;ecx用于存储数组的长度
    call bubbleSort
    call outPutArr
    exit
main ENDP
 
bubbleSort PROC
    push esi ;将用于遍历数组的index压入栈保护
    mov esi,0 ;初始化用于外层循环的index寄存器
    add ecx,1 
    mov ebx,ecx
outloop:
    cmp esi,ecx ;若esi大于等于len则跳出外层循环
    jge final
    mov ebx,ecx 
    sub ebx,esi ;用ebx来存储len-esi-1的值
    sub ebx,1
    mov edi,0 ;初始化用于内层循环的index寄存器
inloop:
    cmp edi,ebx ;若edi大于等于ebx则跳出内层循环
    jge nextoutloop
    ;注意两个内存变量不能直接比较,将其中一个赋值给寄存器后比较
    mov eax,[edx+edi*4]
    cmp eax,[edx+edi*4+4]
    jle nextinloop
    ;注意此处交换元素入栈和出栈的顺序
    push dword ptr [edx+edi*4]
    push dword ptr [edx+edi*4+4]
    pop dword ptr [edx+edi*4]
    pop dword ptr [edx+edi*4+4]
nextinloop:
    add edi,1 ;将内层循环index加1后继续遍历
    jmp inloop
nextoutloop:
    add esi,1 ;将外层循环index加1后继续遍历
    jmp outloop
final:
    pop esi ;在遍历结束的时候将esi弹出栈
    ret
bubbleSort ENDP
 
outPutArr PROC
    push esi ;用esi来存储遍历数组用的index值
    mov esi,0 ;初始化index
again:
    cmp esi,ecx ;若esi大于等于数组长度则结束遍历
    jge final
    mov eax,[edx+esi*4] ;将当前数组元素的值存储在eax寄存器中用于输出
    call writeint
    add esi,1
    jmp again
final:
    pop esi
    ret
outPutArr ENDP
 
END main

运行结果:

在这里插入图片描述

评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋说

感谢打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值