Reputation: 81
I'm learning c language and I wrote a function like this to sort an array.
void sort(int a[], int n)
{
for (int *i = a; i < a + n - 1; i ++)
{
int *j, temp, *max = i;
for (j = i + 1; j < a + n; j ++)
{
if (j > max)
{
max = j;
}
}
if (*max != *i)
{
temp = *i;
*i = *max;
*max = temp;
}
}
return;
}
When I used the function to sort an array like this:
int arr[10] = {12, 34, 5, 689, -43, 56, -21, 0, 24, 65};
sort(arr, 10);
It gave the wrong answer:
12 34 5 689 -43 56 -21 0 24 65
65 12 34 5 689 -43 56 -21 0 24
I checked the code for several times. However, I still can't find where is wrong. Could you please help me with the problem?
Upvotes: 2
Views: 67
Reputation: 41045
if (j > max)
{
max = j;
}
Here you are comparing pointers, not values, change to:
if (*j > *max)
Upvotes: 4