An array is sorted (in ascending order) if each element of the array is less than or equal to the next element .
An array of size 0 or 1 is sorted
Compare the first two elements of the array ; if they are out of order, the array is not sorted; otherwise, check the if the rest of the array is sorted.
Write a boolean -valued method named isSorted that accepts an integer array , and the number of elements in the array and returns whether the array is sorted.

Respuesta :

Answer:

// The program below checks if an array is sorted or not

// Program is written in C++ Programming Language.

// Comments are used for explanatory purpose

//Program Starts here

#include<iostream>

using namespace std;

//Function to check if the array is sorted starts here

int isSorted(int arr[], int count)

{

// Check if arrays has one or no elements

if (count == 1 || count == 0) {

return 1;

}

else

{

// Check first two elements

if(arr[0] >= arr[1])

{

return 0; // Not sorted

}

else

{ // Check other elements

int check = 0;

for(int I = 1; I<count; I++){

if (arr[I-1] > arr[I]) { // Equal number are allowed

check++; // Not sorted

}

}

}

if(check==0)

return isSorted(arr, count - 1); //Sorted

else

return 0; // Not sorted

}

// Main Method starts here

int main()

{

int count;

cin<<count;

int arr[count];

for(int I = 1; I<=count; I++)

{

cin>>arr[I-1];

}

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

if (isSorted(arr, n))

cout << "Array is sorted";

else

cout << "Array is not sorted";

}