2014-09-22 37 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