Array is sorted or not GFG
package com.company;
public class Array4 {
// Efficient method
public static boolean isSorted(int[] arr) {
int largest = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[largest] <= arr[i]) {
largest = i;
}
}
return (largest == arr.length - 1);
}
// Array is sorted or not Time complexity = Big O(n^2)
public static boolean sorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
int[] array = {3, 3, 4, 6, 0};
System.out.println(isSorted(array));
}
}
Comments
Post a Comment