1
\$\begingroup\$

Please let me know if there is a shorter way to do it again without any kind of loops. Recursion only.

static bool isSortedArray (int[] ar, int length)
{
 if (length == 0)
 return true;
 bool temp = isSortedArray(ar, length - 1);
 if (temp && ar[length - 1] <= ar[length])
 return true;
 else
 return false;
}
Brythan
7,0143 gold badges21 silver badges37 bronze badges
asked Apr 4, 2015 at 15:53
\$\endgroup\$
8
  • \$\begingroup\$ possible duplicate of Checking if an array is sorted \$\endgroup\$ Commented Apr 4, 2015 at 16:22
  • \$\begingroup\$ Nope, because it's with only recursion... \$\endgroup\$ Commented Apr 4, 2015 at 16:23
  • \$\begingroup\$ What language is this? Please add a language tag. \$\endgroup\$ Commented Apr 4, 2015 at 16:29
  • \$\begingroup\$ Strange I'v added them O_o anyway fixed... \$\endgroup\$ Commented Apr 4, 2015 at 16:30
  • \$\begingroup\$ Is this Java or C#? It can't be both. \$\endgroup\$ Commented Apr 4, 2015 at 16:42

1 Answer 1

1
\$\begingroup\$

Based on the naming guidelines methods should be named using PascalCase casing.


If you evaluate two conditions connected by && you should always evaluate the faster one first. You can return the result of the condition directly.

This can be reached if you forget the temp variable and rearange the condition like

static bool isSortedArray (int[] ar, int length)
{
 if (length == 0) 
 {
 return true;
 }
 return ar[length - 1] <= ar[length] && isSortedArray(ar, length - 1);
} 

You should also take care of the posibility that ar will be null or that the number of elements is smaller than length.


Using braces {} for single if..else statements will make your code less error prone.


ar as a parametername is not well choosen. You shouldn't shorten parameter names.

isSortedArray should be better named IsArraySorted.


A construct like

if (condition) 
{
 return true;
}
else
{
 // more code here
} 

will always make the else redundant because if the condition is true it will never be reached.

answered Apr 4, 2015 at 22:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.