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
运行结果:

1万+





