Sunday, 23 August 2015

Recursively find whether array is ordered or not


Write a program to find whether array is sorted or not (Check for both ascending, descending arrays).
import java.util.Objects;

public class ArrayOrderCheck {

 public static boolean isOrderedArray(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length < 2)
   return true;

  if (arr[0] > arr[1])
   return checkDescending(arr, 0);
  return checkAscending(arr, 0);
 }

 private static boolean checkDescending(int arr[], int index) {
  if (index == arr.length - 2)
   return arr[index] >= arr[index + 1];
  return (arr[index] >= arr[index + 1])
    && checkDescending(arr, index + 1);
 }

 private static boolean checkAscending(int arr[], int index) {
  if (index == arr.length - 2)
   return arr[index] <= arr[index + 1];
  return (arr[index] <= arr[index + 1]) && checkAscending(arr, index + 1);
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ArrayOrderCheckTest {

 @Test
 public void test1() {
  int arr1[] = { 1, 2, 3, 4, 5 };
  int arr2[] = { 5, 4, 3, 2, 1 };
  int arr3[] = { 1, 2, 3, 4, 5, 6, 1 };
  int arr4[] = {};
  int arr5[] = { 1 };
  int arr6[] = { 5, 4, 3, 2, 3, 4 };
  int arr7[] = { 1, 1, 2, 2, 2, 3, 4 };
  int arr8[] = { 5, 4, 4, 4, 3, 2, 1 };

  assertTrue(ArrayOrderCheck.isOrderedArray(arr1));
  assertTrue(ArrayOrderCheck.isOrderedArray(arr2));
  assertFalse(ArrayOrderCheck.isOrderedArray(arr3));
  assertTrue(ArrayOrderCheck.isOrderedArray(arr4));
  assertTrue(ArrayOrderCheck.isOrderedArray(arr5));
  assertFalse(ArrayOrderCheck.isOrderedArray(arr6));
  assertTrue(ArrayOrderCheck.isOrderedArray(arr7));
  assertTrue(ArrayOrderCheck.isOrderedArray(arr8));
 }
}


No comments:

Post a Comment