Bubble sort using array of structures

i have an assignment in class and we have to take a program we coded and re-arrange it so it puts the output in descending order by units sold. This is the code i have and it works i just need to reorder the output. it should out put:

Product Number Units Sold Unit Price

14 842 12.95
17 514 16.95
18 437 21.95
15 416 14.95
19 269 31.95
16 127 18.95
20 97 14.95




#include <iostream>
#include <string>
#include <iomanip>


using namespace std;

void showArray(int a[], float b[], int c[], int size);
void sortArray(int a[], float b[], int c[], int size);

int main()
{
int ProductNum[7] = {14, 15, 16, 17, 18, 19, 20};
float UnitPrice[7] = {12.95, 14.95, 18.95, 16.95, 21.95, 31.95, 14.95};
int UnitSold[7] = {842, 416, 127, 514, 437, 269, 97};
int length = 7;

sortArray(ProductNum, UnitPrice, UnitSold, length);
showArray(ProductNum, UnitPrice, UnitSold, length);

}

void sortArray(int a[], float b[], int c[], int j)
{
bool swap;
int temp;
float t;

do
{
swap = false;
for (int i = 0; i < j; j++)
{
if (c[i] > c[i + 1])
{
temp = c[i];
c[i] = c[i + 1];
c[i + 1] = temp;

temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;

t = b[i];
b[i] = b[i + 1];
b[i + 1] = t;

swap = true;
}
}
} while (swap);

}

void showArray (int a[], float b[], int c[], int size)
{
cout << setw(25) << left << "Product Number" << setw(25) << left << "Units Sold" << setw(25) << left << "Unit Price" << endl << endl;

for (int count = 0; count < size; count++)
cout << setw(25) << left << a[count] << setw(25) << left << c[count] << setw(25) << left << b[count]<<endl;

cout << endl;
}
Last edited on
Hi,

Firstly please use code tags
www.cplusplus.com/articles/jEywvCM9/

Also here's output

Product Number Units Sold Unit Price

15 416 14.95
14 842 12.95
16 127 18.95
17 514 16.95
18 437 21.95
19 269 31.95
20 97 14.95


Do you see what your code does? It only evaluates the first array, thats because then your swap bool changes its state and you skip the rest of do while loop...

The problem is in your sortArray()

PS: welcome to cplusplus.com
Topic archived. No new replies allowed.