对于插入排序的以下实现,当我使用随机函数生成任意输入时,它输出错误,因为一个元素在Picture中错误地显示为突出显示。我努力去理解,但这是错误,但无法弄明白。我的代码中错误是什么?
#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;
}
答案 0 :(得分:2)
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]);
}
此处smallest
实际上尚未被选中,将其置于循环之外:
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]);