Wednesday, 3 May 2017

C Program to check if an array is sorted or not - Recursively

Approach is very simple we will use function check (int array[],int n) start from the end of the array and if the last two elements are sorted then we perform a recursive call with n-1, else return false. If all the elements are found sorted then n will eventually falls to zero and return true. C program along with outputs is given to check is an array is sorted or not.

PROGRAM:
 
#include <stdio.h>
int check(int array[],int n);
int main()
{
   int n,array[10],i;
   printf("\nEnter the value of the n: ");
   scanf("%d",&n);
   printf("\nEnter the array elements: \n");
   for(i=0;i<n;i++)
   {
       scanf("%d",&array[i]);
   }
   printf("\n\n");
   if(check(array,n-1))
   {
       printf("\nArray is sorted");
   }
   else
   {
        printf("\nArray is not sorted");
   }
   return 0;
}
int check(int array[],int n)
{
  if(n==0)
  {
       return 1;
  }
  else
  {
     if(array[n]>array[n-1])
     {
       return check(array,n-1);
     }
     else
     {
       return 0;
     }

  }
}


OUTPUT:


EmoticonEmoticon