此问题在此处已有答案:
Accessing an array out of bounds gives no error, why?(18个答案)
8天前关闭
我的代码中有什么错误,为什么它没有给出正确的输出?
输入
84
1 0 1 2 1 1 0 0 1 2 1 2 1 2 1 0 0 1 1 2 2 0 0 2 2 2 1 1 1 2 0 0 0 2 0 1 1 1 1 0 0 0 2 2 1 2 2 2 0 2 1 1 2 2 0 2 2 1 1 0 0 2 0 2 2 1 0 1 2 0 0 0 0 2 0 2 2 0 2 1 0 0 2 2
字符串
它的正确输出是:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
型
Your Code的输出是:
0-36092119132636100007056629140-858993460214748364-...
#include<iostream>
#include<algorithm>
using namespace std;
void sortArray(int *arr,int n){
int low=0,mid=1,high=n-1;
while(mid<=high){
if(arr[mid]==1){
mid++;
}
else if(arr[mid]==2){
swap(arr[mid],arr[high]);
high--;
}
else{
swap(arr[mid],arr[low]);
mid++,low++;
}
}
for(int i=0;i<n;i++){
cout<<arr[i];
}
}
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[n];
}
sortArray(arr,n);
}
return 0;
}
的字符串
3条答案
按热度按时间nwlqm0z11#
主要问题在于你的输入阅读:
字符串
您正在阅读
arr[n]
,即undefined。您希望使用i
作为索引:型
由于数组将只包含0、1或2,因此也可以简化排序算法:
型
注意:你正在使用一个非标准的扩展。C++标准没有VLA(variable length arrays)。
可变长度数组通常在“堆栈”上分配,并且容易发生堆栈溢出。如果数组的长度太大,则会出现未定义的行为。更糟糕的是,您也无法轻松知道数组的“正确”大小。因此,最好避免使用VLA。您可以使用
std::vector<int>
。v09wglhw2#
你应该尝试一种更好的方法(教科书方法),即计算0,1和2出现的次数,然后按升序分配它们,或者请解释你在代码中使用的方法。
字符串
就时间和空间复杂度而言,这是一种简单有效的方法
mzsu5hc03#
这段代码不会在012210这样的测试用例中执行,因为如果你保持mid=1,那么它就不会比较index=1处的1,它会离开那个,输出将变成010122.([右],[1])但低是在0索引,然后中只是简单地移动,所以错过了从高索引1的值更新,所以使中=0我们的代码将纠正这种情况,这种优化的代码将适用于所有测试用例
字符串