Question #22309

write a c++ program that instantiates a function template that implements
bubble sort on an array of objects

Expert's answer

#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();

}

#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();

}

## Comments

## Leave a comment