1

One of the functions I am doing uses a insertion sort for a two dimensional array with 2 rows and 12 columns. The first row is for student IDs, so there are 12 students total. The second row has the corresponding GPA for each student. I am not sure how to come up with an insertion sort to sort the GPA numbers in ascending order. Any help would be awesome!

I have this so far.

void insertionSort(double avg[][COLS])
{
int current = 1;
int last = COLS - 1;
int temp;
int walker;
int row = 1;

while (current <= last)
{
    temp = avg[row][current];
    walker = current - 1;
    while (walker >= 0
        && temp < avg[row][walker])
    {
        avg[row][walker+1] = avg[row][walker];
        walker = walker - 1;
    }

    avg[row][walker+1] = temp;
    current = current + 1;
}
7
  • what is the problem with the sort you have made ? it seems to be a correct insertion sort? Commented Jan 9, 2016 at 23:44
  • 1
    Are you against the idea to use std::sort()? Commented Jan 9, 2016 at 23:47
  • 1
    My question really is why this is a two dimensional array. Student ID's are alphanumeric, GPA's are floating point. Who came up with such an idea to make a 2d array out of two distinct types? Commented Jan 9, 2016 at 23:53
  • @m7mdbadawy when I try to output the numbers, the numbers are not correct. The number 2.00 shows up for all of them. Commented Jan 9, 2016 at 23:54
  • @PaulMcKenzie the student ID are just numbered from 1 through 12. Student 1 has student ID of 1, student 2 has ID 2, etc. Commented Jan 9, 2016 at 23:55

1 Answer 1

2

Your problem is that temp variable is declared as an int it should be double also you should swap the ids too

void insertionSort(double avg[][COLS])
{
    int current = 1;
    int last = COLS - 1;
    double temp;//this was an int
    int walker;
    int row = 1;

    while (current <= last)
    {
        temp = avg[row][current];
        walker = current - 1;
        while (walker >= 0
                && temp < avg[row][walker])
        {
            avg[row][walker+1] = avg[row][walker];
            avg[row-1][walker+1] = avg[row-1][walker];//swap the id of two students
            walker = walker - 1;
        }

        avg[row][walker+1] = temp;
        avg[row-1][walker+1] = temp;
        current = current + 1;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.