how to solve this sorted array question
Take as input N, the size of an integer array. Take one more input, which is a list of N integers separated by a space, and store that in an array. Write a recursive function which prints true if the array is sorted, and false otherwise
@tanishka972,
You need to take an input of n numbers and store it in an array. After that you need to pass the array to a function and check if the array is sorted or not, using recursion.
Return false if the array is not sorted.
public class hcf_gcd{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int scn=in.nextInt();
int a[]=new int[scn];
}
public static boolean rec(int[] a)
{
int i;
for(i = 0; i < a.length; i++)
{
if (a[i] < a[i+1])
{
return true;
}
else {
return false;
}
}
}
}
IS IT LIKETHIS?
int[] arr=new int[N];
for(int i=0;i<str.length;i++)
{
arr[i]=in.nextInt();
}
System.out.print(isSorted(arr,0));
}
static boolean isSorted(int[] arr,int si)
{
if(si>=arr.length-1)
return true;
boolean res= (arr[si+1]>=arr[si]) && isSorted(arr,si+1);
return res;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
public class Main {
public static boolean isSorted(int[] arr,int i){
if(i==arr.length-1){
return true;
}
if(arr[i]>arr[i+1]){
return false;
}else{
boolean ans=isSorted(arr,i+1);
return ans;
}
}
public static void main(String args[]) {
Scanner scan=new Scanner(System.in);
int N=scan.nextInt();
int[] a=new int[N];
for(int j=0;j<N;j++){
a[j]=scan.nextInt();
}
System.out.println(isSorted(a,0));
}
}
This code is giving me NoSuchElementException again and again. Could u tell where i m wrong??