In: Computer Science
Write function boolean isSorted(int a[], int size). The function returns true if array a is sorted in either ascend order or descend order; false otherwise.
c++
Please follow the below code with inline comments:
bool isSorted(int a[],int size){
int temp[size-1];
bool result = true;
for(int i=0;i<size;i++)
temp[i]=a[i];
sort(a, a+size);//using in build function for sorting the
array.
for(int i=0;i<size;i++){// checking whether array in sorted in
ascending order or not
if(a[i]!=temp[i])
{
result = false;break;
}
}
int j=size-1;
for(int i=0;i<size;i++){// checking array is in descending order
or not
if(a[i]!=temp[j++])
{
result = false;break;
}
}
return result;
}
The full program to test the function is below:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bool isSorted(int a[],int size){
int temp[size-1];
bool result = true;
for(int i=0;i<size;i++)
temp[i]=a[i];
sort(a, a+size);//using in build function for sorting the
array.
for(int i=0;i<size;i++){// checking whether array in sorted in
ascending order or not
if(a[i]!=temp[i])
{
result = false;break;
}
}
int j=size-1;
for(int i=0;i<size;i++){// checking array is in descending order
or not
if(a[i]!=temp[j++])
{
result = false;break;
}
}
return result;
}
int main()
{
int arr[]={1,2,4,5};
int size = 4;
bool result = isSorted(arr,size);
cout <<"\n"<< result;
return 0;
}
Output:
0 means false
1 means true.