簡體   English   中英

將排序數組代碼從 C++ 轉換為 MIPS 匯編語言

[英]Converting sorting array code from C++ to MIPS assembly language

我在學校有一個練習,將 C++ 代碼轉換為 MIPS 匯編語言。 我對某些函數或過程中的參數有一些問題。 代碼是對一個最多包含 5 個成員的數組進行排序,練習在 c++ 中有三個函數。 第一個是創建一個function,它通過輸入在數組中添加數字,是一個葉子過程,另外兩個功能是對數組進行排序。 這兩個函數是匯編語言中的嵌套過程,我真的不明白如何實現它們,我不明白的是如何將 5 個參數發送到另一個過程,如下面的代碼。

#include <iostream>
#include <string>
using namespace std;

int addElements(int a[])
{
    int n;
    cout << "Enter the size of array: "; 
    cin >> n;
    cout << "\nAdd elements one by one: \n";
    for (int i = 1; i <= n; i++) {
    cin >>a[i];
}

void secondFunction(int p, int n, int &min, int a[], int &loc)
{
    for (int k = p + 1; k <= n; k++)
    {
       if (min > a[k])
       {
          min = a[k];
          loc = k;
       }  
    }
 }
void firstFunction(int a[], int n)
{
    int min, loc, tmp;
    for (int p = 1; p <= n - 1; p++) // Loop for Pass
    {
        min = a[p]; // Element Selection
        loc = p;
        secondFunction(p, n, min, a, loc);
        tmp = a[p];
        a[p] = a[loc];
        a[loc] = tmp;
    }
    cout << "\nPrinting array: \n";
    for (int i = 1; i <= n; i++) {
        cout << a[i] << endl;
    }
}

int main()
{
    int a[5], n = 0;
    n = addElements(a);
    firstFunction(a, n);

}
firstFunction:

  la   $s2,myArr

  la   $s3,myArr
  
  li   $t9,0            #index for loop

  li   $t3,1

  sub  $t3,$t0,$t3

  jal  loop

loop:

  #min=a[p] not passing this as argument,have made it a global variable
  
  lw   $s0,0($s2)   

  move $a0,$t9         
 #s0 is min and a0 is loc (p)
  
  #t0 is n, $s2 is myArr -these I have made global var as they are used throughout the program

  #the only argument passed to second Function is p that I have saved in $a0

  
  jal  secondFun

back4:

  lw    $s1, 0($s2)   #s1 is tmp

  sll   $t7,$a0,2       #index of array at a0

  addu  $t7,$t7,$s3

  lw    $t5,0($t7)

  sw    $t5,0($s2)

  sw    $s1,0($t7)

  addi  $t9,$t9,1

  addi  $s2,$s2,4

  blt   $t9,$t3,loop

  jal   print

 secondFun:

  addi  $t2,$a0,1

  jal   loop2

loop2:
  sll   $t8,$t2,2       #index of array at a0

  addu  $t8,$t8,$s3

  lw    $t6,0($t8)

  blt   $t6,$s0,innerif

back3:

  addi  $t2,$t2,1

  blt   $t2,$t0,loop2

  jal   back4

innerif:

  lw    $s0,0($t8)

  move  $a0,$t2

  jal   back3

我希望這會有所幫助,請隨時糾正我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM