In: Computer Science
php please
// 5) isArraySorted
// Given an array , return true if the element are in ascending order.
// Note: 'abe' < 'ben' and 5 > 3
// Precondition $arr has all the same type of elements
function isArraySorted($arr) {
}
echo PHP_EOL . 'isArraySorted(array(1, 2, 2, 99) 1: ' . isArraySorted ( array (
1,
2,
2,
99 ) ) . "\n";
assert ( isArraySorted ( array (
1,
2,
2,
99 ) ) );
echo 'isArraySorted(array(2, 2, 1) false: ' . isArraySorted ( array (
2,
2,
1 ) ) . "\n";
The solution for the above problem is given below with the screenshots for indentation and if you feel any problem then feel free to ask.
<?php
// defining a function isArraySorted and passing an array into it as argument
function isArraySorted($arr)
{
// storing the size of array in separate variable
$n = sizeof($arr);
// returning true if the size of array is 1 or 0
if($n<2)
{
return "true";
}
else {
// loop for returning if any greater value is occured before smaller value relative to it
for ($i=0; $i < $n-1 ; $i++) {
if ($arr[$i] > $arr[$i+1])
{
return "false";
}
}
//returning true if no greater value occured before smaller one
// implying the array is in ascending order
return "true";
}
}
echo PHP_EOL . 'isArraySorted(array(1, 2, 2, 99) 1: ' . isArraySorted ( array (1,2,2,99 ) ) . "\n";
assert ( isArraySorted ( array (1,2,2,99 ) ) );
echo 'isArraySorted(array(2, 2, 1) false: ' . isArraySorted ( array (2,2,1 ) ) ."\n";
?>
NOTE:- If you want to print true or false then this is for that as it is returning true/false as strings but if you want to get the boolean values then you can change the return statement simply from "true"/"false" to true/false. But in the case of bool the echo command do not produce output for false and for true it generates 1.