check if array is sorted

In this article, we are going to check if the array is sorted using java.

Example:-

If arr=[1,2,3,4,5], then the output will be yes. because it is sorted.

if arr=[2,4,6,10,8], then the output will be no. because it is not sorted.

Steps:-

  • Take the input for the size of an array.
  • Declare an array of a given size.
  • Take the input for the array elements.
  • Run a loop to iterate all the elements.
  • inside the loop check if the current element is smaller then the previous element then return false.
  • End of loop
  • Return true.

Java code to check if array is sorted or not:-

package gangforcode;
import java.util.*;
public class SortedArray {
	public static boolean is_sorted(int[]a,int n) {
		for(int i=1;i<n;i++) {
			if(a[i]<a[i-1]) {
				return false;}}
			
			return true;
		}
		
	

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		 System.out.println("Enter the size of array");
		int n=sc.nextInt();
		 int []a = new int[n];
        for(int i=0;i<n;i++) {
        	a[i]=sc.nextInt();}
          boolean ans= is_sorted(a,n);
          if(ans==true) {
        	  System.out.println("Yes");}
        	  else {
        		  System.out.println("No");
        	  }
          }
        	
        
	}


Output:-

check if array is sorted or not.

You can use the same logic to check if the array is sorted or not using other programming languages

Leave a Comment