Sunday, August 20, 2017

Checking if the given number is already sorted in Java

About this program it will check if the given list of numbers stored in one dimensional array is already sorted or not using Java. It will return if the given list of numbers is already sorted and false is the given number is not yet sorted.

I hope you will find my work useful and beneficial. If you have some questions about programming, about my work please send mu an email at jakerpomperada@gmail.com and jakerpomperada@yahoo.com. People here in the Philippines can contact me at  my mobile number 09173084360.

Thank you very much and Happy Programming.




Sample Program Output



Program Listing

sorted.java


package exam;

public class sorted {

public static boolean CheckSorted(int[] val_num){
   boolean checkSorted = true;
   boolean isAscending = val_num[1] > val_num[0];
   if(isAscending) {
       for (int a = 0; a < val_num.length-1; a++) {
           if(val_num[a] > val_num[a+1]) {
               checkSorted= false;
               break;
           }           
       }
   } else {
       for (int b = 0; b < val_num.length-1; b++) {
           if(val_num[b] < val_num[b+1]) {
               checkSorted = false;
               break;
           }           
       }  
   }    
   return checkSorted;
}
public static void main(String[] args) {
         
        
         int list_values1[] = new int[]{2,3,3,4,5};
        
         int list_values2[] = new int[]{10,-5,75,4,8,53};
         
         System.out.println();
         System.out.print("Checking if the given number is already sorted in Java");
         System.out.println("\n\n");
         System.out.print(CheckSorted(list_values1));
         System.out.println();
         System.out.print(CheckSorted(list_values2));
        
     
      
 }

}




No comments:

Post a Comment