Array Sorting?

trying to write a function that sorts an array in ascending order but whenever I run the function in the main it does not sort. Can anyone see anything wrong with this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void sortArray( int quizArray[], int quiz_number )
{
    int i, j, min;
    int temp;
    for (i = 0; i <= quiz_number; i++)
    { min = i;
        for (j= i + 1; j < quiz_number; j++)
        {
            if(quizArray[i] < quizArray[min])
            {min =j;}
        }
        temp = quizArray[i];
        quizArray[i] = quizArray[min];
        quizArray[min] = temp;
    }
}
show the code for your function call in main()
Shouldn't your "swap" be inside the if() statement?

The following snippet will probably access your array out of bounds when i is equal to quiz_number.
for (i = 0; i <= quiz_number; i++)

What happens if i is equal to quiz_number - 1 or higher?
for (j= i + 1; j < quiz_number; j++)

The swap should be just where it is, there should just be an if( min != i ){ swap } around it.

also, line 9 should be if( quizArray[j] < quizArray[min] )
Last edited on
Thanks! I had the line 9 error and a curly bracket in the wrong spot. Here's the corrected code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void sortArray( int quizArray[], int quiz_number )
{
    int i, j, min;
    int temp;
    for (i = 0; i < quiz_number - 1; i++)
    { min = i;
        
        for (j= i + 1; j < quiz_number; j++)
        {
            if(quizArray[j] < quizArray[min])
            {min =j;}
        }
        temp = quizArray[i];
        quizArray[i] = quizArray[min];
        quizArray[min] = temp;
    }

}
nice. A nearly perfect example of: http://en.wikipedia.org/wiki/Selection_sort
Topic archived. No new replies allowed.