|
-
May 27th, 2002, 06:46 AM
#1
question about Insertion sort
Hello... I have a question This is my code for Insertion sort...
But it doesn't work... I don't know What the problem is...
The output is
-30000
1
2
3
but it should be
1
2
3
4
I need help... Thanks in advance
#include <stdio.h>
#define MAXINT 30000
typedef struct {
int stud_id;
char name[10];
char grade[4];
}student;
void Insertion(int , student* );
void main()
{
int i;
student std[5] =
{{1000, "xxxxxx ", "A+ "},
{4, "aaaaaaa", "A+"},
{3, "bbbbbb", "A0"},
{1, "ccccccc", "A0"},
{2, "ddddddd", "B0"}};
Insertion(5, std);
for(i = 1; i < 5; i++)
printf("%d\n", (std + i)->stud_id);
}
void Insertion(int n, student* s)
{
int i, j, r;
s->stud_id = -MAXINT;
for(i = 2; i <= n; i++)
{
j = i - 1;
r = (s + i)->stud_id;
while(r < (s + j)->stud_id)
{
(s + j + 1)->stud_id = (s + j)
->stud_id;
j = j - 1;
}
(s + j + 1)->stud_id = r;
}
}
-
May 27th, 2002, 05:45 PM
#2
The loop runs one time more than it should, because of the error in the the loop condition. It should be i < n instead of i <= n.
When n is 5 (with your test data), you're reading one element pasted the end of the array 's'.
Happy hacking,
Jonas
-
May 27th, 2002, 06:07 PM
#3
Thanks
Your reply is really helpful... Thank you...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|