Thread: using insertion sort to sort a database by age

  1. #1
    Registered User
    Join Date
    Apr 2014
    Posts
    1

    using insertion sort to sort a database by age

    Hi,
    I am trying to sort a student database by age,but i am not sure whats wrong i think it has to deal with tmpstudent variable.

    Code:
    void insertion_sort(StudentDB *db)
    {
        int i;
        for (i = 0; i < db->num; ++i)
        {
            int j = i - 1;
            int val = db->records[i].age;
            Student *tmpStudent = &db->records[i];
            while (j >= 0 && val < db->records[j].age)
            {
                db->records[j + 1] = db->records[j];
                j--;
    
            }
    
            db->records[j + 1] = *tmpStudent;
    
        }
    }
    Last edited by codemonkey2013; 04-29-2014 at 04:23 PM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    A few things that would help in the future:

    • Describe the problem. Does it mostly sort the data, does it crash, does it print out garbage?
    • Provide a small but complete/compilable program so we can test.
    • Provide a small sample input that demonstrates the problem, again to help us test your code.


    I suspect you're right in terms of tmpStudent. It seems tmpStudent merely points at records[i] so you don't actually copy the data. When you shift all the elements up one spot to make room to insert, you have overwritten db->records[i] (which is what tmpStudent points at). Thus, when you do db->records[j + 1] = *tmpsStudent; you are not inserting the correct data.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. insertion sort vs shell sort
    By johnmerlino in forum C Programming
    Replies: 34
    Last Post: 04-28-2014, 06:41 PM
  2. Insertion Sort
    By peripatein in forum C Programming
    Replies: 0
    Last Post: 03-02-2014, 02:54 AM
  3. Insertion sort
    By yogesh2 in forum C++ Programming
    Replies: 0
    Last Post: 02-11-2013, 11:45 AM
  4. Replies: 1
    Last Post: 01-26-2010, 09:02 AM
  5. Insertion Sort Help
    By Odinwar in forum C++ Programming
    Replies: 8
    Last Post: 12-09-2009, 11:27 AM