dimanche 7 janvier 2018

Why does the for loop in selection sort have n-1 steps instead of n? C++

I have the following attempt to write a selection sort in C++:

#include <iostream>

using namespace std;

int main()
{
    int a[10], k, i, j,n, aux;
    cin>>n;
    for (i=1; i<=n; i++)
        cin>>a[i];
    k=a[1];
    for(i=1; i<=n-1; i++)
    {for (j=i+1; j<=n;j++)
        if (k>a[j])
            k=a[j];
    for(j=i+1; j<=n; j++)
            if (k==a[j])
            {aux=a[i];
            a[i]=a[j];
            a[j]=aux;}
    k=a[i+1];}
    for(i=1; i<=n; i++)
        cout<<a[i];
        return 0;
}

From my tests it returns sorted arrays, so I think it's correct.

But I also have to explain why the main for loop of the sort only takes n-1 steps instead of n. Could anyone explain the "why" part to me?

Aucun commentaire:

Enregistrer un commentaire