In: Computer Science
[jAVA] Assume the following array is defined and initialized (it will already contain numbers before your code runs):
public static void main( String [ ] args ) {
int [ ] numbers = . . . ; // An array of integers
1) Provide code that will print the entire contents of numbers in reverse order (from the end to the beginning)
2) Provide code that will print true if the numbers are in strictly ascending order (that is, if starting from the start of the array each item has a larger value than the one that came before it) and print false otherwise.
Java Code
public class Main
{
static int arraySortedOrNot(int numbers[], int n)
{
// Array has one or no element or the
// rest are already checked and approved.
if (n == 1 || n == 0)
return 1;
// Unsorted pair found (Equal values allowed)
if (numbers[n - 1] < numbers[n - 2])
return 0;
// Last pair was sorted
// Keep on checking
return arraySortedOrNot(numbers, n - 1);
}
// main function
public static void main(String[] args)
{
int numbers[] = { 20, 23, 23, 45, 78, 88 };
int n = numbers.length;
int i;
System.out.println("Original array: ");
for (i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
for (i = numbers.length-1; i >= 0; i--) //Loop through the array
in reverse order
{
System.out.print(numbers[i] + " ");
}
System.out.println();
System.out.println("Array is sorted or not :");
if (arraySortedOrNot(numbers, n) != 0)//To check array is sorted or
not
System.out.println("True");
else
System.out.println("False");
}
}
Output
Original array:
20 23 23 45 78 88
Array in reverse order:
88 78 45 23 23 20
Array is sorted or not :
True