2014-09-22 56 views
-1

对于以下实施插入排序当我使用随机函数来生成任意输入时,它给出了错误的输出,因为一个元素出现错误地放置为突出显示在图片中。我努力去理解,然而却是错误,但无法弄清楚。什么是错误在我的代码?选择为一个元素排序C++错误的输出?

enter image description here

#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

这听起来像是一个完美的机会来学习如何使用调试器。 – NPE 2014-09-22 10:14:26

+0

应该是这样的:for(current = 0; current Galik 2014-09-22 10:19:05

+0

@Galik仍然给出错误的输出 – 2014-09-22 10:20:23

回答

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]); 
+0

糟糕:)谢谢..! – 2014-09-22 10:22:46