Hello guys,
I'm studying arrays... I came across this very common problem which is sorting an array. OK, Here's what I have got so far:
Code:
#include <stdio.h>
void sort_list(int list[])
{
int i, j, temp, length = sizeof(list)/sizeof(int);
for(i = 0; i < length - 1; i++)
{
for(j = i + 1; j < length; j++)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
int main(void)
{
int values[] = {6, 2, 7, 11, 50, 12, 8};
sort_list(values);
int i = 0;
for(i = 0; i < sizeof(values)/sizeof(int); i++)
printf("%d\r\n", values[i]);
return 0;
}
But the output was:
I am surprised
The output is like as there is not something called sort_list
when I changed the version to be:
Code:
#include <stdio.h>
void sort_list(int list[])
{
int i, j, temp, length = sizeof(list)/sizeof(int);
for(i = 0; i < length - 1; i++)
{
for(j = i + 1; j < length; j++)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
for(i = 0; i < sizeof(list)/sizeof(int); i++)
printf("%d\r\n", list[i]);
}
int main(void)
{
int values[] = {6, 2, 7, 11, 50, 12, 8};
sort_list(values);
int i = 0;
for(i = 0; i < sizeof(values)/sizeof(int); i++)
printf("%d\r\n", values[i]);
return 0;
}
The output was more surprising:
a new 6 plus the first observation!!
another version - which worked -:
Code:
#include <stdio.h>
void sort_list(int list[], int n)
{
int i, j, temp;
for(i = 0; i < n - 1; i++)
{
for(j = i + 1; j < n; j++)
{
if(list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
for(i = 0; i < n; i++)
printf("%d\r\n", list[i]);
}
int main(void)
{
int values[7] = {6, 2, 7, 11, 50, 12, 8};
sort_list(values, 7);
int i = 0;
return 0;
}
Now, the main difference between the working version and the others is passing the number of elements as a parameter to the sorting function... why is that so important that the function doesn't work unless it is present?
Thanks in advance