1. 程式人生 > >彙編:氣泡排序

彙編:氣泡排序

 求的一個數組的最大值:

.section .data
data_items:
.long 3,67,54,99
.section .text
.globl _start
_start:
        nop
	movl $0, %edi
	movl data_items(,%edi,4), %eax
	movl %eax, %ebx
	start_loop:
	cmpl $0, %eax #比較eax的值是不是0,是0則跳出迴圈,最後一個元素為0
	je loop_exit
	inc %edi
	movl data_items(, %edi,4), %eax
	cmpl %ebx, %eax
	jle start_loop
	movl %eax, %ebx
	jmp start_loop
	loop_exit:
	mov $1, %eax
        int $0x80

 輸出某個佇列的全部元素:

.section .data
values:
    .int 12, 35, 99, 18, 76
length:
    .int 5
output:
    .asciz "The sorted values are:"
outputvalues:
    .asciz " %d %d %d %d %d\n"
.section .text
.global _start
_start: 
    nop
    movl length, %ecx
    pushl $output
    call printf
    movl length, %ecx
    subl $1, %ecx
loop_values:    
    pushl values(, %ecx, 4)
    loop loop_values  #loop直到ecx暫存器為0
    pushl values
    pushl $outputvalues
    call printf
    addl $28, %esp
    movl $1, %eax
    movl $0, %ebx
    int $0x80

 氣泡排序:

# sort-maopao.s - An example of  using 
.section .data
values:
    .int 12, 35, 99, 18, 76
length:
    .int 5
output:
    .asciz "The sorted values are:"
outputvalues:
    .asciz " %d %d %d %d %d\n"
.section .text
.global _start
_start: 
    nop 
    movl length, %ecx # control outside circle
    movl length, %edx # control inside circle
    subl $1, %ecx
    subl $1, %edx
    movl $values, %esi
loop:
    movl (%esi), %eax
    cmpl %eax, 4(%esi)
    jge skip#小於或者等於則跳轉
    xchg %eax, 4(%esi)
    movl %eax, (%esi)
skip:
    add $4, %esi
    dec %ecx
    jnz loop
    dec %edx
    jz print_values
    
    movl $values, %esi
    movl %edx, %ecx
    jmp loop#無條件轉移指令
print_values: 
    pushl $output
    call printf
    movl length, %ecx
    subl $1, %ecx
loop_values:    
    pushl values(, %ecx, 4)
    loop loop_values
    pushl values
    pushl $outputvalues
    call printf
    addl $28, %esp
    movl $1, %eax
    movl $0, %ebx
    int $0x80