C++ 显示排序模拟

C++ 显示排序模拟,c++,sorting,bubble-sort,C++,Sorting,Bubble Sort,我试图展示这个冒泡排序的模拟,我使用了一个函数交换程序,它有参考值,但当我在交换后尝试打印它时,它也会打印出内存地址。我怎样才能解决这个问题 void swapper(int &a, int &b) { int temp = a; a = b; b = temp; return; } int main(){ //Bubble sort int arr[] = {-2, 45, 0, 11, -9}; int n = 5; for(int step =

我试图展示这个冒泡排序的模拟,我使用了一个函数交换程序,它有参考值,但当我在交换后尝试打印它时,它也会打印出内存地址。我怎样才能解决这个问题

void swapper(int &a, int &b) {
  int temp = a;
  a = b;
  b = temp;

  return;
}

int main(){

//Bubble sort

int arr[] = {-2, 45, 0, 11, -9};
int n = 5;


for(int step = 0; step < n-1; step++) {

  for(int i = 0; i < n; i++) {
    if(arr[i] > arr[i + 1])
       swapper(arr[i], arr[i + 1]);
  }

  for(int x = 0; x < n; x++)
      cout << arr[x] << " ";

  cout << endl;

}
void交换程序(int&a、int&b){
内部温度=a;
a=b;
b=温度;
返回;
}
int main(){
//气泡排序
int arr[]={-2,45,0,11,-9};
int n=5;
对于(int step=0;steparr[i+1])
交换程序(arr[i],arr[i+1]);
}
对于(int x=0;x
#include <iostream>
using namespace std;

void swapper(int &a, int &b) {
  int temp = a;
  a = b;
  b = temp;

  return;
}

int main(){

    //Bubble sort

    int arr[] = {-2, 45, 0, 11, -9};
    int n = 5;


    for(int step = 0; step < n-1; step++) {

        for(int i = 0; i+1 < n; i++) {
            if(arr[i] > arr[i + 1])
                swapper(arr[i], arr[i + 1]);
        }

        for(int x = 0; x < n; x++)
            cout << arr[x] << " ";

        cout << endl;
    }
}
调整输出 您可以通过替换

cout << arr[x] << " ";
修复错误 试试这个:

#include <iostream>
using namespace std;

void swapper(int &a, int &b) {
  int temp = a;
  a = b;
  b = temp;

  return;
}

int main(){

    //Bubble sort

    int arr[] = {-2, 45, 0, 11, -9};
    int n = 5;


    for(int step = 0; step < n-1; step++) {

        for(int i = 0; i+1 < n; i++) {
            if(arr[i] > arr[i + 1])
                swapper(arr[i], arr[i + 1]);
        }

        for(int x = 0; x < n; x++)
            cout << arr[x] << " ";

        cout << endl;
    }
}
调整输出 您可以通过替换

cout << arr[x] << " ";

1) 示例末尾缺少一个
}
。2)代码中的UB:reading
arr[i+1]
for
i==n-1
reads out-of-bounds。1)示例末尾缺少一个
}
。2) .UB在您的代码中:读取
arr[i+1]
for
i==n-1
读取超出范围。感谢帮助谢谢帮助
#include <iomanip>
-2  0 11 -9 45 
-2  0 -9 11 45 
-2 -9  0 11 45 
-9 -2  0 11 45