Change insertion sort to descending instead of ascending?
May 6, 2018 at 5:38pm UTC
I am using an insertion sort on an array of objects. I have it working right now, but it is in ascending order and I want descending. How can I fix this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
void insertion_sort(Invoice invoices[], const int NUM_ITEMS)
{
int j;
Invoice temp;
for (int i = 0; i < NUM_ITEMS; i++)
{
j = i;
while (j > 0 && invoices[j].getPrice() < invoices[j - 1].getPrice())
{
temp = invoices[j];
invoices[j] = invoices[j - 1];
invoices[j - 1] = temp;
j--;
}
}
cout << endl;
for (int i = 0; i < NUM_ITEMS; i++)
{
cout << invoices[i].getNum();
cout << setw(11) << "\t" << invoices[i].getDes();
cout << setw(11) << "\t" << invoices[i].getQuan();
cout << setprecision(2) << fixed << setw(11) << "\t$" << invoices[i].getPrice() << endl;
}
}
May 6, 2018 at 5:44pm UTC
I think you just need to reverse the test in the while loop
while (j > 0 && invoices[j].getPrice() > invoices[j - 1].getPrice())
Topic archived. No new replies allowed.