Сделать проверку массива на возрастание/убывание

Как сделать проверку массива на возрастание/убывание на С++?


Ответы (1 шт):

Автор решения: ТарасПрогер
#include<iostream>

enum Sort
{
    Ascending, // возрастание
    Descending // убывание
};

template<typename T>
bool CheckIfSorted(T t[], int len, Sort type)
{
    if (type == Ascending)
    {
        for (int i = 0; i < len-1; ++i)
        {
            if (!(t[i] < t[i+1]))
            {
                return false;
            }
        }
    }
    else if (type == Descending)
    {
        for (int i = 0; i < len-1; ++i)
        {
            if (!(t[i] > t[i+1]))
            {
                return false;
            }
        }
    }
    return true;
}


int main()
{
    float arr[3] = { 1.0f,2.0f,3.0f };
    if (CheckIfSorted<float>(arr, 3, Ascending) == true)
    {
        std::cout << "Sorted Ascending" << std::endl;
    }
    if (CheckIfSorted<float>(arr, 3, Descending) == true)
    {
        std::cout << "Sorted Descending" << std::endl;
    }
    system("pause");
    return 0;
}
→ Ссылка