我从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();
}
听起来好像您可能需要学习如何使用调试器来逐步执行代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
我看到交换没有正确完成你的情况。 –
“给一个问题”...你至少可以具体说明问题所在。 – crashmstr