Custom Search

Tuesday, November 4, 2008

Using an array of structs and Bubble_sort

#include <iostream>

#include <iomanip>

using namespace std;

#define SIZE 6

struct tankvol {

double radius;

double length;

};

struct tankcar {

tankvol capacity;

double weight;

char type;

};


 

void get_cars(tankcar c[], int n);

void print_cars(tankcar c[], int n);

void sort_cars_by_radius(tankcar c[], int n);


 

int main()

{tankcar cars[SIZE];


 

get_cars(cars, SIZE);


 

print_cars(cars, SIZE);


 

sort_cars_by_radius(cars, SIZE);


 

print_cars(cars, SIZE);


 

return 0;

}


 


 

void get_cars(tankcar c[], int n)

{int i;

for(i=0; i < n; ++i)

{ cout<< "enter radius, length, weight,type\n";

cin>> c[i].capacity.radius >>c[i].capacity.length >>c[i].weight

>>c[i].type;

}

}


 

void print_cars(tankcar c[], int n)

{int i;

cout<< "radius length weight type\n\n";

for(i=0; i < n; ++i)

{

cout<< setw(4)<<c[i].capacity.radius<<setw(10)

<<c[i].capacity.length<<setw(9)

<< c[i].weight<<setw(10)<< c[i].type << endl;

}

}


 


 

/* Bubble sort with early exit when no swaps*/

void sort_cars_by_radius(tankcar c[], int n)

{

tankcar temp;

int i,j,swapsmade=1;


 

for( i=n; i >=2 && swapsmade ; --i)

{ cout<<"i is:"<<i<<endl;

swapsmade = 0;

for(j=0; j < i-1; ++j)

{ cout<<"j is:"<<j<<endl;            //these couts purpose is trace

cout << "comparing:"<<c[j].capacity.radius <<"with:"

<<c[j+1].capacity.radius<<endl;

if(c[j].capacity.radius > c[j+1].capacity.radius)

{ temp = c[j];

c[j]=c[j+1];

c[j+1] = temp;

swapsmade =1;

}

}

}

}

[pt@cs aix]$

[pt@cs aix]$ a.out

enter radius, length, weight,type

4 2 56 a

enter radius, length, weight,type

5 5 60 b

enter radius, length, weight,type

45 20 100 c

enter radius, length, weight,type

3 4 66 a

enter radius, length, weight,type

6 4 77 q

enter radius, length, weight,type

7 8 33 a

radius length weight type


 

4 2 56 a

5 5 60 b

45 20 100 c

3 4 66 a

6 4 77 q

7 8 33 a

i is:6

j is:0

comparing:4with:5

j is:1

comparing:5with:45

j is:2

comparing:45with:3

j is:3

comparing:45with:6

j is:4

comparing:45with:7

i is:5

j is:0

comparing:4with:5

j is:1

comparing:5with:3

j is:2

comparing:5with:6

j is:3

comparing:6with:7

i is:4

j is:0

comparing:4with:3

j is:1

comparing:4with:5

j is:2

comparing:5with:6

i is:3

j is:0

comparing:3with:4

j is:1

comparing:4with:5

radius length weight type


 

3 4 66 a

4 2 56 a

5 5 60 b

6 4 77 q

7 8 33 a

45 20 100 c


 

No comments: