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;
}
-
\$\begingroup\$ possible duplicate of Checking if an array is sorted \$\endgroup\$m0nhawk– m0nhawk2015年04月04日 16:22:29 +00:00Commented Apr 4, 2015 at 16:22
-
\$\begingroup\$ Nope, because it's with only recursion... \$\endgroup\$BananaBuisness– BananaBuisness2015年04月04日 16:23:54 +00:00Commented Apr 4, 2015 at 16:23
-
\$\begingroup\$ What language is this? Please add a language tag. \$\endgroup\$200_success– 200_success2015年04月04日 16:29:09 +00:00Commented Apr 4, 2015 at 16:29
-
\$\begingroup\$ Strange I'v added them O_o anyway fixed... \$\endgroup\$BananaBuisness– BananaBuisness2015年04月04日 16:30:08 +00:00Commented Apr 4, 2015 at 16:30
-
\$\begingroup\$ Is this Java or C#? It can't be both. \$\endgroup\$nhgrif– nhgrif2015年04月04日 16:42:43 +00:00Commented Apr 4, 2015 at 16:42
1 Answer 1
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.