Hi guys,

I'm trying to write a recursive method that checks if the first elements of an array of integers are sorted in ascending order but it didn't work for me !!

public static Boolean isSorted(int [] a, int n){}

I tried to copy elements from array a with length n into another array b then , compare every two elements starting from b[0] and b[1] such that :

if (b[0] < b[1] ) // that means those elements are in ascending order
{ return true;
}

but I couldn't complete it ,, could anyone please help me :(

you are super close. Do you have to check for both ascending and descending or just one.

Edited 5 Years Ago by Gerbiler: n/a

Why do you need to write this recursively? It would be much simpler with a single loop. Also, recursive methods tend to be much slower and more memory-intensive than their iterative equivalents.

Gerbiler , I know I can feel the answer but I can't catch it :)

I checked for ascending order only ,,

could please help me writing the rest of the code ?


death_oclock

I know and undersand what you said , but I'm studying recursion now and I must write this method recursively

any help with writing the rest of the code will be appreciated

Here's a hint:
Start at the nth element. If that's <= the n-1th element then it's not ascending.
If its >, then you can go on to check (n-1) against (n-2) etc
until you get down to elements 2 vs 1.

Edited 5 Years Ago by JamesCherrill: n/a

JamesCherrill , I did it ok for n and n-1 but how am I supposed to do it for n-1 and n-2 without copying the array into array of length n ? the method takes an array and an integer as parameters .
!!

I'm really stuck!

This article has been dead for over six months. Start a new discussion instead.