Skip to content

Commit 382a1f1

Browse files
Check if array is sorted
1 parent 356b02d commit 382a1f1

3 files changed

Lines changed: 85 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package array.check_if_array_is_sorted;
2+
3+
/**
4+
* Utility class that provides a method to check
5+
* whether an integer array is sorted in non-decreasing (ascending) order.
6+
*/
7+
public class CheckSorted {
8+
9+
/**
10+
* Checks whether the given array is sorted in ascending order.
11+
*
12+
* <p>An array is considered sorted if:
13+
* <ul>
14+
* <li>It is {@code null}</li>
15+
* <li>It has zero or one element</li>
16+
* <li>Every element is less than or equal to the next element</li>
17+
* </ul>
18+
*
19+
* @param nums the array of integers to check
20+
* @return {@code true} if the array is sorted or null; {@code false} otherwise
21+
*/
22+
public boolean checkSorted(int[] nums) {
23+
if (nums == null || nums.length <= 1) {
24+
return true;
25+
}
26+
for (int i = 0; i < nums.length - 1; i++) {
27+
if (nums[i] > nums[i + 1]) {
28+
return false;
29+
}
30+
}
31+
return true;
32+
}
33+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/**
2+
* Provides utilities for performing checks on arrays.
3+
*
4+
* <p>This package currently includes functionality to determine
5+
* whether an integer array is sorted in ascending order.
6+
*/
7+
package array.check_if_array_is_sorted;
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package array.check_if_array_is_sorted;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
class CheckSortedTest {
8+
9+
private final CheckSorted checker = new CheckSorted();
10+
11+
@Test
12+
void testNullArray() {
13+
assertTrue(checker.checkSorted(null));
14+
}
15+
16+
@Test
17+
void testEmptyArray() {
18+
assertTrue(checker.checkSorted(new int[]{}));
19+
}
20+
21+
@Test
22+
void testSingleElementArray() {
23+
assertTrue(checker.checkSorted(new int[]{5}));
24+
}
25+
26+
@Test
27+
void testAlreadySortedArray() {
28+
assertTrue(checker.checkSorted(new int[]{1, 2, 3, 4, 5}));
29+
}
30+
31+
@Test
32+
void testArrayWithDuplicates() {
33+
assertTrue(checker.checkSorted(new int[]{1, 2, 2, 3, 3}));
34+
}
35+
36+
@Test
37+
void testUnsortedArray() {
38+
assertFalse(checker.checkSorted(new int[]{3, 1, 4, 2}));
39+
}
40+
41+
@Test
42+
void testDescendingArray() {
43+
assertFalse(checker.checkSorted(new int[]{5, 4, 3, 2, 1}));
44+
}
45+
}

0 commit comments

Comments
 (0)