CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2002
    Location
    KR
    Posts
    36

    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;
    }
    }

  2. #2
    Join Date
    Aug 2001
    Location
    Stockholm, Sweden
    Posts
    1,664

    Exclamation

    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

  3. #3
    Join Date
    May 2002
    Location
    KR
    Posts
    36

    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
  •  





Click Here to Expand Forum to Full Width

Featured