'Code using RISC-V a program that finds the smallest value in the sequence and swaps it with the first value
The question is : Given a sequence of non-zero integers followed by 0, find the smallest integer in the sequence then swap it with the integer in the beginning of the sequence. Use the DD assembler command to store in the beginning of the memory the initial test sequence of 121, 33, -5, 242, -45, -12, 0. Save your solution as a file named bex2b.asm for possible future use
Problem: I understand how to find the smallest value but I am stuck on how to swap the value with the first value of the sequence.
src: DD -1, 5, -3, 7, 0
add x6, x0, x0
ld x7, src(x6)
addi x5, x7, 0
beq x5, x0, end
loop: blt x7, x5, skip
addi x7, x5, 0
skip: addi x6, x6, 8
ld x5, src(x6)
bne x5, x0, loop
end: addi x5, x7, 0
ebreak x0, x0, 0
some help on this would be appreciated
Solution 1:[1]
You will have to write to memory. The instruction set does not offer a single "swap the values of two memory locations" instruction, and whenever you cannot do something in one, you compose a sequence to do it in more.
Capture both values from memory into CPU registers, then write the first value into the location where you got the second one, and vice versa: write the second value into the location where you got the first one.
You'll need to manipulate both the values and their storage locations to accomplish that, so you'll have to know or remember what the first value is, as well as where the first value is located, and know or remember what the smallest value is, as well as where the smallest value is located.
There is no need to think in assembly for this algorithm. It can be worked out in C with pointers or in C with indexes, and in other languages with indexes. (Pointers would be natural to use for this.) Working this out in C and then translating to assembly would be easier than thinking in assembly when you don't know the language yet.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
