数组在 C++ 中不使用 static in 函数时不会修改

array not modifying without using static in function in c++

本文关键字:函数 in 修改 static C++ 数组      更新时间:2023-10-16

因为数组名称就像指向数组起始地址的指针,所以当传递给函数时,为什么数组没有修改。当我使用静态指针只存储数组的地址时。之后,使用数组名称返回数组不会引起任何问题。为什么会这样?

#include<iostream>
using namespace std;
int main()
{
int a[10]={2,16,19,20,2,9,18};
int* bubble(int [],int);
cout<<"the sorted array is ";
int n=10;
int *ma=bubble(a,n);
for(int i=0;i<10;i++)
{
cout<<ma[i]<<'n';
}
return 0;
}
int* bubble(int *a,int n)
{
int no_of_comparisons;
int ptr,temp;
static int *ma=a;
while(no_of_comparisons<=n-1-1)
{
ptr=0;
while(ptr<=n-1-no_of_comparisons-1)
{
if(a[ptr]>a[ptr+1])
{
temp=a[ptr];
a[ptr]=a[ptr+1];
a[ptr+1]=temp;
}
ptr+=1;
}
no_of_comparisons+=1;
}
return a;
}

顺便说一下,气泡排序是最简单的算法,也是非常大的输入中最慢的算法。基本思想是,只是遍历从 i=0 到 n 的数组,如果相邻元素顺序不正常,则交换相邻元素。下面我重写了您的代码,使其更具可读性、清晰和简短。我希望它有帮助。

#include<iostream>
int* bubble(int [], int);
int main()
{
int arr[10] = {2, 16, 19, 20, 28, 9, 18, 22, 32,1};
int arr_size = 10;
std::cout << "Original Array: n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< 'n';
bubble(arr, arr_size);
std::cout << "Sorted Array: n";
for(int i = 0; i < 10; i++)
std::cout << arr[ i ]<< 'n';
return 0;
}
int* bubble(int *a, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = n - 1; j > i; j--)
{
if( a[j] < a[j - 1] )
{
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
return a;
}

代码中的主要问题是,首先没有初始化no_of_comparisons变量。在你的情况下,我认为应该是0

相关文章: