我的插入排序代码有问题
There's something wrong with my Insertion Sort code
我从mycodeschool那里学到了这种实现,方法对我来说似乎还可以,因为那是那里的讲师的教学方式,我做了相同的实现,但我的代码以某种方式给出了一个问题,也请只需忽略时间函数,因为错误在其他地方。我删除了它,错误仍然相同。
//insertion sort
#include<iostream>
#include <ctime>
using namespace std;
class insertion{
public:
insertion(){} //constructor
void sort(int a[], int n) { //insertion sort function
for (int i = 1; i < n; i++) {
int value = a[i];
int index = i;
while (i > 0 && a[i - 1] > value) {
a[index] = a[index - 1];
index=index-1;
}
a[index] = value;
}
}
//display function
void display(int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << endl;
}
}
};
void main(){
insertion ins;
int a[10];
int n = 10;
cout << "Enter the elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
unsigned int start = clock(); //measuring time of sort from here
cout << "waiting for keyhit";
cin.ignore();
ins.sort(a, n);
ins.display(a, n);
cout << "Time taken in millisecs: " << clock() - start; //to here
cin.ignore();
}
我可以看到的一个错误是您在循环的终止状态下对i的使用不正确。您应该使用变量索引,我认为这也是您的最初意图。
我描述了校正后,您可能会在此处观察到的正如其他主()所观察到的那样,您的排序功能似乎有效。下面,您可能会在校正之后看到排序函数的定义。
void sort(int a[], int n) { //insertion sort function
for (int i = 1; i < n; i++) {
int value = a[i];
int index = i;
while (index > 0 && a[index - 1] > value) {
a[index] = a[index - 1];
index=index-1;
}
a[index] = value;
}
}
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 我在范围内未声明的错误类有问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 我在 c++ 中的 AES 代码有问题。明文正在更改,但加密邮件是相同的。我找不到我的错误
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 我的编辑距离递归代码中的字符类型有问题
- 中止陷阱 - 我的代码有问题
- C++ 我的代码有问题
- 有人可以解释一下这个 c++ 代码的作用吗?结构有问题
- 我的插入排序代码有问题
- 我的代码中的数组有问题.任何建议
- 霍夫曼代码,树的初始输入有问题
- 我有一个 c++ 代码,它在启动时崩溃,然后到达问题所在 main() 的执行
- 彩票应用程序,代码有问题
- 这怎么可能是竞态条件.或者是我的代码有问题
- C++:使用变量派生.一小部分代码有问题
- 二进制搜索中的一段代码在c++中似乎有问题
- 我的代码有问题,因为我无法弄清楚为什么会收到错误。这是代码: