-1
对于以下实施插入排序当我使用随机函数来生成任意输入时,它给出了错误的输出,因为一个元素出现错误地放置为突出显示在图片中。我努力去理解,然而却是错误,但无法弄清楚。什么是错误在我的代码?选择为一个元素排序C++错误的输出?
#include<iostream>
#include<cstdlib>
using namespace std;
template <class Item>
void exch(Item &A, Item &B)
{
Item t = A ;
A = B;
B = t;
}
template<class Item>
void selection(Item list[],int last)
{
Item holdData;
int smallest,current,walker;
for(current=0;current<=last;current++)
{
smallest = current;
for(walker=current+1;walker<=last;walker++)
{
if(list[walker] < list[smallest])
smallest = walker;
//smallest selected, exhange with the current
exch(list[smallest],list[current]);
}
}
}
int main()
{
int N = 20;
int *a = new int[N];
for(int i=0;i<N;i++) a[i] = 1000*(1.0*rand()/RAND_MAX);
cout<<"Before sorting : \n";
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
selection(a,N-1);
cout<<"\n\nAfter Sorting : \n";
for(int i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
这听起来像是一个完美的机会来学习如何使用调试器。 – NPE 2014-09-22 10:14:26
应该是这样的:for(current = 0; current
Galik
2014-09-22 10:19:05
@Galik仍然给出错误的输出 – 2014-09-22 10:20:23