选择排序C ++错误输出一个元素?

时间:2014-09-22 10:10:09

标签: c++ sorting selection-sort

对于插入排序的以下实现,当我使用随机函数生成任意输入时,它输出错误,因为一个元素在Picture中错误地显示为突出显示。我努力去理解,但这是错误,但无法弄明白。我的代码中错误是什么?

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;
}

1 个答案:

答案 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]);