Answer to Question #22309 in Action Script | Flash | Flex | ColdFusion for Juel Samaddar

Question #22309
write a c++ program that instantiates a function template that implements
bubble sort on an array of objects
1
Expert's answer
2013-01-21T10:43:57-0500
#include <cmath>
#include <conio.h>
#include <iostream>

using namespace std;

struct Vector
{
int x, y;

double GetLength()
{
return sqrt((double)this->x * this->x + this->y * this->y);
}

void Display()
{
cout << '(' << x << ", " << y << ')';
}

bool operator < (Vector& point)
{
return (this->GetLength() < point.GetLength());
}
};

template <class T>
void bubble_sort(T array[], int length)
{
T tmp;
for (int i = 0; i < length; i++)
for (int j = 1; j < length - i; j++)
if (array[j - 1] < array[j])
{
tmp = array[j - 1];
array[j - 1] = array[j];
array[j] = tmp;
}
}

void main()
{
Vector array[4] = { {2, -8}, {-6, 3},& {7, 1}, {2, 3} };

cout << "Initial array of vectors:" << endl;
array[0].Display(); cout << ", ";
array[1].Display(); cout << ", ";
array[2].Display(); cout << ", ";
array[3].Display(); cout << endl << endl;

bubble_sort(array, 4);

cout << "Sorted array of vectors:" << endl;
array[0].Display(); cout << ", ";
array[1].Display(); cout << ", ";
array[2].Display(); cout << ", ";
array[3].Display(); cout << endl;

getch();
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS