I need a c++ program that is able to determine whether or not a given array is sorted in ascending or descending order. then after that the program should reverse the direction of order

Recommended Answers

All 3 Replies

Ditto rproffitt, but have you considered there is a possible third state? What if the array is not sorted at all? What happens then? If you are guaranteed that it is sorted then you only have to check the first two elements, or the first and last to determine the direction, assuming the items are unique. If the number of elements is one or zero then the problem becomes trivial.

But you'll still need to implement a sort.

commented: well if its not sorted the output should say "array is not sorted" and if it is it should say that then reverse the direction +0

This should do what you asked.

#include <iostream>
using namespace std;

int main()
{
    int n, i, arr[50], flag = 0;
    cout << "Enter the size of array: ";
    cin >> n;
    cout << "Enter the elements of array: ";
    for (i = 0; i < n; i++)
        cin >> arr[i];
    for (i = 1; i < n; i++)
    {
        if (arr[i] > arr[i - 1])
        {
            flag = 1;
            break;
        }
    }
    if (flag == 0)
        cout << "The array is sorted in descending order." << endl;
    else
    {
        flag = 0;
        for (i = 1; i < n; i++)
        {
            if (arr[i] < arr[i - 1])
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            cout << "The array is sorted in ascending order." << endl;
        else
            cout << "The array is not sorted." << endl;
    }
    cout << "The reversed array is: ";
    for (i = n - 1; i >= 0; i--)
        cout << arr[i] << " ";
    return 0;
}

Enter the size of array: 5
Enter the elements of array: 5
4
3
2
1
The array is sorted in descending order.
The reversed array is: 1 2 3 4 5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.