- 2068 Baisakh · 6 marks
Array class template with max, min, sort
Short answer
Define a class template Array with dynamic array. Member functions maximum() and minimum() iterate to find extremes; sort() uses bubble sort. Works for any type supporting > and <.
Write a program with a class template to represent array and add member functions to find maximum, minimum and sort the generic array.
#include <iostream>
using namespace std;
template <class T>
class Array {
T *a;
int n;
public:
Array(int size) {
n = size;
a = new T[n];
}
~Array() { delete[] a; }
void read() {
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) cin >> a[i];
}
T maximum() {
T m = a[0];
for (int i = 1; i < n; i++)
if (a[i] > m) m = a[i];
return m;
}
T minimum() {
T m = a[0];
for (int i = 1; i < n; i++)
if (a[i] < m) m = a[i];
return m;
}
void sort() { // ascending bubble sort
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - 1 - i; j++)
if (a[j] > a[j + 1]) {
T t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
void display() {
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << endl;
}
};
int main() {
Array<int> x(5);
x.read();
cout << "Max = " << x.maximum() << ", Min = " << x.minimum() << endl;
x.sort();
cout << "Sorted: "; x.display();
Array<float> y(4);
y.read();
cout << "Max = " << y.maximum() << ", Min = " << y.minimum() << endl;
y.sort();
cout << "Sorted: "; y.display();
return 0;
}
The same class works for int and float (and any type that supports > and <).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Time class: add two objects · Object Oriented Programming, chapter 1
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Class template with multiple template types · Object Oriented Programming, chapter 9
- Class template with suitable example · Object Oriented Programming, chapter 9
- Default arguments in class template · Object Oriented Programming, chapter 9
- Function template: sum and average of array · Object Oriented Programming, chapter 9
- Array overflow/underflow; add two arrays · Computer Programming, chapter 7
- Sort array ascending in FORTRAN · Computer Programming, chapter 11 · asked 2×
- Sort array using a function · Computer Programming, chapter 7
- Correct program: case array and average · Computer Programming, chapter 3