Reputation: 283
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;
}
Upvotes: 1
Views: 1568
Reputation: 920
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;
}
}
Upvotes: 2