Code to sort an array of numbers with emu 8086
- User
Code to sort an array of numbers with emu 8086
- Assistant
Here is an example of code to sort an array of numbers in ascending order using emu 8086:
.stack 100h .data array db 5,2,4,3,1 n equ 5 .code main proc ; display original array mov ah, 09h lea dx, original int 21h ; call sorting procedure call sort_array ; display sorted array mov ah, 09h lea dx, sorted int 21h ; exit program mov ah, 4ch int 21h main endp ; procedure to sort array in ascending order sort_array proc mov cx, n ; initialize loop counter mov bx, 1 ; initialize array index loop1: mov si, bx ; copy array index to SI mov al, array[bx] ; initialize temporary storage loop2: cmp si, 1 ; check if at first element jle skip_swap ; if so, skip swap dec si ; move to previous element mov dl, array[si] ; compare current element with next element cmp al, dl jge skip_swap ; if current element >= next element, skip swap mov array[si+1], dl ; swap elements jmp loop2 skip_swap: mov array[si+1], al ; store current element in correct position inc bx ; move to next element loop loop1 ret original db 'Original array:',13,10 db '$' sorted db 13,10,'Sorted array:',13,10 db '$' end mainThe above code initializes an array of 5 numbers, prints the original array, sorts the array in ascending order, then displays the sorted array. The
sort_arrayprocedure uses nested loops to compare adjacent elements and swap them if they are out of order. The outer loop iterates through each element of the array, and the inner loop compares each element with the previous element and swaps them if they are in the wrong order. After sorting the array, the procedure returns to the main program.Note: This code is for demonstration purposes only and may not be optimized for performance or error-free. It is recommended to test and debug thoroughly before using in production code.