想问一下,编写一个插入排序函数,然后在主函数测试,这个程序哪里错了
源代码如下
#include
using namespace std;
void order(int a[12], int n) {
for (int i = 2; i <= n; i++) {
int j, x = a[i];
for (j = i; j > 1 && a[j - 1] > x; j--) {
a[j] = a[j - 1];
}
a[j] = x;
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
}
int main() {
int a[5] = { 2,1,4,5,7 };
int n = sizeof(a) / sizeof(a[0]);
order(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
程序没有报错,运行的时候系统崩了
改动处见注释,供参考:
#include <iostream>
using namespace std;
void order(int a[12], int n) {
for (int i = 1; i < n; i++) { //(int i = 2; i <= n; i++) 修改
int j, x = a[i];
for (j = i; j > 0 && a[j - 1] > x; j--) { //for (j = i; j > 1 && a[j - 1] > x; j--) 修改
a[j] = a[j - 1];
}
a[j] = x;
}
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout<<endl; //修改
}
int main() {
int a[5] = { 2,1,4,5,7 };
int n = sizeof(a) / sizeof(a[0]);
order(a, n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:这里有问题,只有a[0]到a[4]共5个数,当 i = 5时,访问 a[i] 就会出错。
for (int i = 2; i <= n; i++) {
int j, x = a[i];