0

I have read other answers to this question and tried all of the different implementations. Most of the time, the numbers that generate(), well, generates become 0 after the sort. I cannot find the error. Here is my code:

void sort(int values[], int n)
{
    int min=0;
    int temp;
    for (int i =0; i < n-1; i++)
    {
        min = values[i];
        for (int j=i+1; j<n-1; j++)
        {
            if (values[j]<values[min])
            {
                min = values[j];
            }
        }
        temp = values[i];
        values[i]=values[min];
        values[min]=temp;
    }
    // TODO: implement an O(n^2) sorting algorithm
    return;
}
0
2

There is definitely a problem in the sort code. The logic is flawed because it is using min to store the minimum value at times and to store the index of the minimum value at other times. By mixing them, it's corrupting the array. This is also how 0's are getting into the sorted list. Instead of assigning value[i] or value[j] to min, it should be simply i or j.

There's also a secondary problem that the last element in the list isn't being sorted, but this is an easy fix that you should quickly find.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .