0

I wrote this c++ function to sort an array, it works, but it doesn't seem to work with the fist value: it isalways the bigger instead of the smaller!

    void s_iSort (double a[])
    {
        cout << "INCREASING SORTER:\n\n";
        unsigned int mx,maxx;
        double temp;
        cout << "Insert maximum element to sort: "; cin>>mx;
        for (int c=0; c<mx; c++)
            {
                maxx=0;
                for (int i=c; i<mx; i++)
                    if (a[i]<a[maxx])
                        maxx=i;
                temp=a[c];
                a[c]=a[maxx];
                a[maxx]=temp;

            }
        cout << "\nDONE!\n\n";
    }

What's worng with this?

2
  • Please provide a minimal reproducible example (you are already close to that) and the input, expected and actual output Commented Oct 9, 2016 at 10:47
  • On the first round if (a[i]<a[maxx]) will be the same as if (a[0]<a[0]). And then you never visit the first element again. Commented Oct 9, 2016 at 10:52

1 Answer 1

1

You should either use a debugger, or try to explain your algorithm to a rubber duck. However, I am in a rubber duck mood and will point you to a mistake:

for (int c=0; c<mx; c++) {
    maxx=0;
    for (int i=c; i<mx; i++) if (a[i]<a[maxx]) maxx=i;
    temp=a[c];
    a[c]=a[maxx];
    a[maxx]=temp;
}

In each iteration of this loop you want to go trough a range of elements, find the minimum value in that range and put it as the first element of that range. It works for the first iteration, but already on the second it goes wrong. You initialize maxx (which is supposed to be the first element in that range) to 0, ie the first element of the array. However you should only consider elements that have not yet been sorted, ie change it to

maxx = c;

Also note, that (apart from exercises) you should not write your own sorting algorithm but use std::sort.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.