program to check the array is sorted or not..

----Naive approach----

 #include <iostream>


bool ifsorted(int arr[], int size)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = i + 1; j < size; j++)
        {
            if (arr[i] > arr[j])
                return false;
        }
    }
    return true;
}

int main()
{
    std::cout << "Cheking if the array is sorted or not" << std::endl;
    int arr[] = {1, 222, 20, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    std::cout << ifsorted(arr, size) << std::endl;
    std::cin.get();
}

----Efficient approach----
#include <iostream>
using namespace std;

bool isSorted(int arr[], int n)
{
    if (n == 0 || n == 1)
        return true;
    for (int i = 1; i < n; i++)
        if (arr[i - 1] > arr[i])
            return false;
    return true;
}

int main()
{
    int arr[] = {22, 23, 100};
    int n = sizeof(arr) / sizeof(arr[0]);
    if (isSorted(arr, n))
        cout << "Yes\n";
    else
        cout << "No\n";
}

Post a Comment

0 Comments