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;
}
\$\endgroup\$
  • \$\begingroup\$ possible duplicate of Checking if an array is sorted \$\endgroup\$ – m0nhawk Apr 4 '15 at 16:22
  • \$\begingroup\$ Nope, because it's with only recursion... \$\endgroup\$ – BananaBuisness Apr 4 '15 at 16:23
  • \$\begingroup\$ What language is this? Please add a language tag. \$\endgroup\$ – 200_success Apr 4 '15 at 16:29
  • \$\begingroup\$ Strange I'v added them O_o anyway fixed... \$\endgroup\$ – BananaBuisness Apr 4 '15 at 16:30
  • \$\begingroup\$ Is this Java or C#? It can't be both. \$\endgroup\$ – nhgrif Apr 4 '15 at 16:42
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.