近期遇到作业需要使用RISK-V来编程实现快速排序,但是查询了一下没有找到相关帖,所以把我的发布出来当成笔记也可以给跟我一样需要的人参考一下。
//摘抄于王道数据结构教材(侵删)
int Partition(int A[], int low, int high)
{
int pivot = A[low];
while (low < high)
{
while (low < high && A[high] >= pivot)
{
high--;
}
A[low] = A[high]; // 比枢轴元素小的元素移动到左端
while (low < high && A[low] <= pivot)
{
low++;
}
A[high] = A[low]; // 比枢轴元素大的元素移动到右端
}
A[low] = pivot; // 枢轴元素放到最终位置
return low; // 枢轴元素的最终位置,左边元素小于枢轴元素,右边元素大于枢轴元素
}
void QuickSort(int A[], int low, int high)
{
if (low < high)
{
int pivotPos = Partition(A, low, high); // 进行一次划分
QuickSort(A, low, pivotPos - 1); // 递归划分左边部分
QuickSort(A, pivotPos + 1, high); // 递归划分右边部分
}
}
.data
# the list wait to be sorted
list: .word 1, 10, 2, 7, 6, 10, 9, 8
# the length of list
length: .word 8
comma: .asciz ", "
.macro ReadInt
li a7,5
ecall
.end_macro
.macro PrintInt
li a7,1
ecall
.end_macro
.macro PrintStr
li a7, 4
ecall
.end_macro
.macro Save(%r)
addi sp, sp, -4
sw %r, 0(sp)
.end_macro
.macro Restore(%r)
lw %r, 0(sp)
addi sp, sp, 4
.end_macro
.text
j main
partition:
# t0 is i = left_index * 4
addi t0, a4, 0
# t1 is j = right_index * 4
addi t1, a5, 0
# t2 is p = A[i]
add t2, a2, t0
lw t2, 0(t2)
part_loop_1:
bge t0, t1, partition_return
part_loop_j:
# t3 = A[j]
add t3, a2, t1
lw t3, 0(t3)
bge t0, t1, part_loop_j_end
ble t3, t2, part_loop_j_end
addi t1, t1, -4
j part_loop_j
# A[i] = A[j]
part_loop_j_end:
# t3 = A[j]
add t3, a2, t1
lw t3, 0(t3)
# t4 = address of A[i]
add t4, a2, t0
sw t3, 0(t4)
part_loop_i:
# t3 = A[i]
add t3, a2, t0
lw t3, 0(t3)
bge t0, t1, part_loop_i_end
bgt t3, t2, part_loop_i_end
addi t0, t0, 4
j part_loop_i
# A[j] = A[i]
part_loop_i_end:
# t3 = A[i]
add t3, a2, t0
lw t3, 0(t3)
# t4 = address of A[j]
add t4, a2, t1
sw t3, 0(t4)
j part_loop_1
partition_return:
# t3 = address of A[i]
add t3, a2, t0
# A[i] = p
sw t2, 0(t3)
# pivot(a6) = i, return i
addi a6, t0, 0
jr ra
qsort:
bge a4, a5, qsort_return
Save(ra)
jal ra, partition
Restore(ra)
# qsort(A,left,p-1)
Save(ra)
Save(a4)
Save(a5)
Save(a6)
addi a5, a6, -4
jal qsort
Restore(a6)
Restore(a5)
Restore(a4)
Restore(ra)
# qsort(A,p+1,right)
Save(ra)
Save(a4)
Save(a5)
Save(a6)
addi a4, a6, 4
jal qsort
Restore(a6)
Restore(a5)
Restore(a4)
Restore(ra)
qsort_return:
jr ra
list_print:
# t3 store list[0] address
addi t3, a2, 0
# t4 is index
li t4, 0
rp_loop:
beq t4, a3, rp_return
lw a0, 0(t3)
addi t3, t3, 4
addi t4, t4, 1
PrintInt
# if it is last number, do not print comma
beq t4, a3, not_print_comma
la a0, comma
PrintStr
not_print_comma:
j rp_loop
rp_return:
jr ra
main:
# a2 store list[0] address
la a2, list
# a3 store length of list
lw a3, length
# a4 = left_index * 4
addi a4, zero, 0
# a5 = right_index * 4
addi t0, t0, 4
mul a5, a3, t0
addi a5, a5, -4
# a6 = pivot * 4
# quick sort
jal ra, qsort
# print result
jal ra, list_print
实现方法有些复杂,可以参考后改进