Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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