user3020469
user3020469

Reputation:

Check to see if array is sorted recursively in java

I want to write a method (returning a boolean value) named itisSorted that takes two arguments;

 and recursively checks whether the array is sorted. That is, returning true if (and only if) the data array is sorted.

public boolean itisSorted(int [] data, int n)
{
  if(data.length ==0 || data.length==1) 
  return true;
  else if (data[n] > data[n-1]) //here i compare the first two elements 
  return false;
   else //here is where i put the recursive call to check if 
    // the rest of the array is sorted, but I am having difficulties with the 
    // part of the code
}

Upvotes: 1

Views: 9785

Answers (4)

Fher Moj
Fher Moj

Reputation: 11

//with this method there is no need to pass the length of the array

public static boolean isOrdered(int nums[])
{
    // Base Cases
    if (nums.length == 0)
        return true;
    if (nums.length == 1)
        return true;

    int[] temp = new int[nums.length - 1];

    if (nums[0] <= nums[1]) {
        for (int i = 1; i < nums.length; i++) {
            temp[i-1] = nums[i];
        }
        return isSorted(temp);
    } else 
        return false;

}

Upvotes: 1

Sunil Namdev
Sunil Namdev

Reputation: 11

Solution using recursion

int isArraySorted(int []a, int index)
{
    if(index == 1 || a.length == 1)
        return 1;
    return (a[index -1] <= a[index-2]) ? 0 : isArraySorted(a, index-1) ;
}

change the condition for descending accordingly.

Upvotes: 1

what is sleep
what is sleep

Reputation: 905

 public boolean itisSorted(int [] data, int n)
{
if(data.length ==0 || data.length==1) 
  return true;
else if (data[n] > data[n-1]) //here i compare the first two elements 
  return false;
 else
 {
  if(n==data.length-1)
  {
      return true;
  }
  return itisSorted(data, n+1); //recursion, checks next integer in the array
 }

is this the answer you want?

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

I think you want something like this

public static boolean itisSorted(int[] data, int n) {
  // Null or less then 2 elements is sorted.
  if (data == null || n < 2) {
    return true;
  } else if (data[n - 2] > data[n - 1]) {
    // If the element before (n-2) this one (n-1) is greater,
    return false;
  }
  // recurse.
  return itisSorted(data, n - 1);
}

public static void main(String[] args) {
  int [] data = {1,2,3};
  System.out.println(Arrays.toString(data) //
      + (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
  data = new int[] {3,2,1};
  System.out.println(Arrays.toString(data) //
      + (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
}

Upvotes: 3

Related Questions