Monday 4 September 2017

Java Code to find the array is in non-descending order or not

Problem:

Implement a function that examines an array and returns the Boolean value sorted which is true if the array is in non-descending order and false otherwise.

Solution:

package array.programs;

import java.util.Scanner;

public class FindTheArraySortedorNot {

int[] array;
int limit;

public static void main(String[] args) {
FindTheArraySortedorNot findTheArraySortedorNot = new FindTheArraySortedorNot();
findTheArraySortedorNot.initilizeTheArray();
findTheArraySortedorNot.printTheArray();
System.out.println();
System.out.println("is sorted array in ascending order?? " + findTheArraySortedorNot.isSortedArray(findTheArraySortedorNot.array));
}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

public boolean isSortedArray(int[] array){
boolean isSortedArray = true;
for (int i = 0; i < array.length - 1; i++) {
for(int j = i+1; j < array.length; j++){
if(array[i] > array[j]){
isSortedArray = false;
break;
}
if(!isSortedArray){
break;
}
}
}
return isSortedArray;
}

}


Output:

enter the array elements limit
5
enter the element
23
enter the element
34
enter the element
45
enter the element
56
enter the element
67
23 34 45 56 67
is sorted array in ascending order?? true


enter the array elements limit
5
enter the element
23
enter the element
33
enter the element
4
enter the element
33
enter the element
22
23 33 4 33 22 
is sorted array in ascending order?? false

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...