c++ - 为插入排序获取有趣的输出
问题描述
我正在尝试实现插入排序。我的逻辑可能是错误的,因为由于某些错误我无法完成我的代码。我需要在执行时值发生荒谬变化的帮助。此外,还有一个类似的重复元素问题,但它在 python 中并且超出了我的想象。所以,请不要将其标记为重复。
如您所见,我已经初始化了一个临时变量索引,您为什么要问?因为N的值在运行期间会发生变化。其次,在进行排序时,值会重复。我正在使用代码块 17.2。
#include<iostream>
#include<utility>
#include<algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int arr[100];
int N,index;
cin>>N;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
index=N; // using temperory variable
for(int l=0;l<index;l++)
{
for(int j=l+1;j>=0;j--)
{
if(l==index-1 || j==0) //Working fine now
break;
if(arr[j]<arr[j-1])
{
swap(arr[j],arr[j-1]);
}
}
cout<<N<<endl; //value of n is changing but why
for(int k=0;k<index;k++)
{
cout<<arr[k]<<" "; //value of array is also coming wrong
}
cout<<"\n";
}
return 0;
}
N=7 并且数组的元素是
7 8 5 2 4 6 3
输出是
7 //这些是正在变化的 N 的值
7 8 5 2 4 6 3
5
7 7 8 2 4 6 3
2
5 7 7 8 4 6 3
2
4 5 7 7 8 6 3
2
4 5 6 7 7 8 3
2
3 4 5 6 7 7 8
0
2 3 4 5 6 7 7
解决方案
检查边界条件,当访问不存在的数组索引时,它将给出未定义的行为。在这种情况下,N 似乎是在 arr 之前存储的,并且在您修改 arr[-1] 时发生了变化。
推荐阅读
- android - 片段中滚动视图内的 RecyclerView 不起作用?
- google-colaboratory - 当我在 Google Colab 中下载包或文件时,会消耗我的数据吗?
- javascript - 更改模式中多个文本框上的事件
- kubernetes - 有没有办法使用 Kubernetes 将容器端口映射到特定的主机端口?
- python - Python语音识别工作非常缓慢并且有很多时间滞后
- python-3.x - 将一列垂直组合到另一列并填充 Pandas 中的其他列值
- xml - 如何在树视图中隐藏自定义按钮
- node.js - 在 React 项目中运行 FFMPEGJS
- javascript - 如何使用猫鼬更新 MongoDB 中的数组?
- javascript - 如何使用 Hooks 在 ReactJS 中设置 API 请求的状态响应