选择排序数组

Selection sort array

我试图让我的程序使用选择排序将最小的数字排序到最大的数字。一切都编译和 运行s,但当我尝试使用该程序时,数字顺序不正确。

你能不能看一下我的程序,看看是否有什么我可以更改以使其 运行 正确,因为我尝试了一切,但它仍然没有按正确的顺序显示数字。

#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;

void makearray(int data[],int n)
{
for ( int i =0 ; i < n ; i++)
    data[i]=(1+rand()%(1000-1+1));
}


template <class item, class sizetype>
int index_of_minimal(const item data[],sizetype i, sizetype n)
{
    int index=i;
    int first=data[i];

    for (i; i < n; i++)
    {
        if (data[i] < first)
            index = i;
    }

    return index;
}


template <class item, class sizetype>
void swap(item data[],sizetype i, sizetype j)
{
    int temp;

    temp=data[i];
    data[i]=data[j];
    data[j]=temp;
}


template <class item, class sizetype>
void selectionsort(item data[], sizetype n)
{
    int j;
    for(int i=0; i< n-1; i++)
    {
        j=index_of_minimal(data,i,n);
        swap(data,i,j);
    }

}

int main()
{
    int n;

    cout << "Enter n: " ;
    cin>>n;
    int data[n];
    makearray(data,n);

    cout << "unsorted array: " ;
    for(int i = 0; i < n; i++)
        cout << data[i] << " ";
    cout << endl;

    selectionsort(data, n);

    cout << "sorted array: " ;
    for(int i = 0; i < n; i++)
        cout << data[i] << " ";
    cout << endl;
    return 0;
}

在你的index_of_minimal函数中,你需要为下一次比较重置当前最小值(first)并保存它的索引,否则在你的迭代中另一个数字,小于原始 first 值可能仍大于您已处理的值。

所以应该是这样的:

for (i; i < n; i++)
{
    if (data[i] < first)
    {
        index = i;
        first=data[i];//also save the new minimum value
    }
}