I have an array who's values were inserted unsorted. Is it possible to print the values from least to greatest or do I need to use insertion sort?
I have an array who's values were inserted unsorted. Is it possible to print the values from least to greatest or do I need to use insertion sort?
It can be done without sorting, though it's usually easier if you do sort it.
Can't you use qsort() in stdlib.h ?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I'll try to see if I can go back and sort on insertion. It's just that I am using a structure that is filled with different types of data from multiple text files and I had finally gotten everything imputed correctly... then I remembered I needed to print it all out sorted by one of the part. I should have planned better. Thinking about touching that part of the code makes me want to bang my head against the wall...
edit:
I was looking through my book and found an example that uses sorts in descending order. However, when I try to modify it to sort in ascending order it I can't get it to work correctly...
How can I modify this so it sorts from least to greatest?
struct{
char name [40];
int number;
float salary;
}
......
int main(void)
{......
data[100].........
}
void bubble(struct employee data[])
{
int i, dum;
for (dum = 0; dum < sizeof(data-1); dum++)
for (i = 0; i < sizeof(data-1); i++)
if (data[i].number < data[i+1].number)
swap(&data[i], &data[i+1]);
}
void swap(struct employee *data1, struct employee *data2)
{
struct employee temp;
temp = *data2;
*data2 = *data1;
*data1 = temp;
}
Last edited by LoveTractor; 11-21-2010 at 03:24 PM.
I was looking through my book and found an example that uses sorts in descending order. However, when I try to modify it to sort in ascending order it I can't get it to work correctly...
How can I modify this so it sorts from least to greatest?
Code:struct{ char name [40]; int number; float salary; } ...... int main(void) {...... data[100]......... } void bubble(struct employee data[]) { int i, dum; for (dum = 0; dum < sizeof(data-1); dum++) for (i = 0; i < sizeof(data-1); i++) if (data[i].number < data[i+1].number) swap(&data[i], &data[i+1]); } void swap(struct employee *data1, struct employee *data2) { struct employee temp; temp = *data2; *data2 = *data1; *data1 = temp; }
Well the big problem at the moment is using sizeof() in an attempt to measure the length of the array.
If that is in the book, then the book is wrong.
Pass the actual length of the array as another parameter to your sort function, and use that parameter in your loop limits.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.