gpt4 book ai didi

c++ - 使用插入排序 C++

转载 作者:行者123 更新时间:2023-11-28 06:28:39 25 4
gpt4 key购买 nike

我写了一个插入排序的代码,似乎没有错误(它编译得很好),但它不打印任何东西或要求用户输入。我已经看过好几次了,但我不明白为什么代码不能正常运行。谢谢!

#include <iostream>
using namespace std;

void getInput(int a[ ], int n);
void insertionSort(int a[ ], int n);
void print(int a[ ], int n);

int main()
{
int n=7;
int a[n];

getInput(a, n);
insertionSort(a, n);
print(a, n);

system("pause");
return 0;
}


void getInput(int a[ ], int n)
{
for(int i; i<n;i++)
{
cout<<"Number? ";
cin>>a[i];
}
}

void insertionSort(int a[ ], int n)
{
int temp, j;
for(int i = 0; i<n; i++)
{
temp = a[i];
j=i;

while(j>0 && a[j-1] > temp)
{
a[j]= a[j-1];
j=j-1;
}
}
}


void print(int a[ ], int n)
{
for(int i= 0; i<n; i++)
{
cout<<a[i]<<" ";
}

cout<<endl;
}

最佳答案

printgetInput 中,您的变量 i 未初始化为 0

你应该将你的 i 初始化为 0

for(int i = 0; i<n;i++)
{
cout<<"Number? ";
cin>>a[i];
}

打印方法相同。

此外,您应该使用 cont var 初始化数组大小。 For more details

const int n = 7;

关于c++ - 使用插入排序 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com