直接插入排序问题
template <class T>
void func(T A[],int n)
{
T temp;
int i,j;
for (i=1;i<n;i++)
{
j = i;
temp = A[i];
while(j>0&&A[j-1])
{
A[j] = A[j-1];
j --;
}
A[j] = temp;
}
}
不懂for循环里面的意思
[解决办法]
汗,才20分啊,明显是一本书上的习题,还打错了while(j>0 &&temp<a[j-1])//如果第二个数据元素数据小于第一个即a[i]<a[i-1]才进入循环,把a[i-1]的值给给a[i],就是把第一个和第二个交换一下位置,然后第3个和第2个,第一个比,比谁小就和谁交换下,
[解决办法]
#include<iostream>#include<fstream>#include<sstream>#include<vector>using namespace std;template <class T> void InsertSort(vector<T>& v) //插入排序{ vector<T> temp; typedef vector<T>::iterator VI; temp.push_back(v[0]); for (VI i = v.begin()+1;i<v.end();++i) { for (VI j = temp.end()-1;j>=temp.begin();--j) { if ((*i)>=(*j)) { temp.insert(j+1,(*i)); break; } if (j==temp.begin()&&(*i)<(*j)) { temp.insert(temp.begin(),(*i));//[color=#800000]问题应该在这里 但是不知道啥问题[/color] } } } v=temp;}void main(){ vector<int> a; a.push_back(1); a.push_back(10); a.push_back(2); a.push_back(5); // int a[5] = {1,2,3,4,5}; for(vector<int>::iterator i=a.begin();i!=a.end();i++){ cout<<*i<<endl; } InsertSort(a); for(vector<int>::iterator j=a.begin();j!=a.end();j++){ cout<<*j<<endl; } system("pause"); // return 0; }