Check if Array is Sorted in Ascending Order with Java Solutions

#Coding4 Q: Check whether a given array is sorted in ascending order. Example: {1, 3, 5, 7, 9} → ✅ Sorted {1, 5, 3, 7} → ❌ Not Sorted I explored 3 different approaches: ✅ 1. Single Pass (Optimal – O(n)) static boolean isSorted(int[] arr) { for(int i = 0; i < arr.length - 1; i++) { if(arr[i] > arr[i + 1]) return false; } return true; } ✅ 2. Using Streams boolean sorted = IntStream.range(0, arr.length - 1).allMatch(i -> arr[i] <= arr[i + 1]); ✅ 3. Compare with Sorted Copy int[] copy = arr.clone(); Arrays.sort(copy); boolean isSorted = Arrays.equals(copy, arr); Key Learnings: Single-pass solution is interview preferred (O(n), O(1)) Streams provide a functional style Sorting approach is simpler but less optimal Practicing fundamentals daily to strengthen problem-solving skills #DSA #Java #Arrays #ProblemSolving #CodingJourney #InterviewPrep #LearningInPublic #LinkedInDSA

To view or add a comment, sign in

Explore content categories