C++ Program to Check if Array is Sorted

Write C++ Program to Check if Array is Sorted

// CPP Program to Check if Array is Sorted

#include <iostream>

using namespace std;

int main()
{
	int A[]={1, 2, 3, 4, 1},i,flag = 0;

	int n = sizeof(A) / sizeof(A[0]);

	cout << "Array A :--> ";
	for(i=0; i<n; i++)
        cout << A[i] << " ";

	for(i = 0;i < n - 1; i++)
	{
		if(A[i] > A[i+1])
		{
			flag = 1;
			break;
		}
	}

	if(flag == 0)
	{
		cout << "\n\nArray is sorted";
	}
	else
	{
		cout << "\n\nArray is not sorted";
	}
	return 0;
}

Output:

Run 1:
Array A :--> 1  2  3  4  5

Array is sorted

Run 2:
Array A :--> 1  2  3  4  1

Array is not sorted

≪ Previous | Next ≫