首页 > 解决方案 > 为插入排序获取有趣的输出

问题描述

我正在尝试实现插入排序。我的逻辑可能是错误的,因为由于某些错误我无法完成我的代码。我需要在执行时值发生荒谬变化的帮助。此外,还有一个类似的重复元素问题,但它在 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

标签: c++insertion-sort

解决方案


检查边界条件,当访问不存在的数组索引时,它将给出未定义的行为。在这种情况下,N 似乎是在 arr 之前存储的,并且在您修改 arr[-1] 时发生了变化。


推荐阅读