Skip to main content

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)

All Object Oriented Programming chapter 9 questions →