由于数组名就像一个指向数组起始地址的指针,所以当传递给一个函数时,为什么数组没有被修改。当我使用只存储数组地址的静态指针时。之后使用其名称返回数组不会引起任何问题。为什么会这样?
#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
。
关于c++ - 在 C++ 函数中不使用 static 不修改数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800721/