Skip to content

Commit 87c12dd

Browse files
author
Ram swaroop
committed
coded + unit tested
1 parent 66574c6 commit 87c12dd

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package me.ramswaroop.arrays.sorting;
2+
3+
/**
4+
* Created by IntelliJ IDEA.
5+
*
6+
* @author: ramswaroop
7+
* @date: 10/23/15
8+
* @time: 8:30 AM
9+
*/
10+
public class CheckSorted {
11+
12+
/**
13+
* Determines whether array {@param a} is sorted or not.
14+
* Sort order can be either ascending or descending.
15+
*
16+
* @param a
17+
* @return
18+
*/
19+
public static boolean isSorted(int[] a) {
20+
21+
if (a.length == 0) return true;
22+
23+
int i;
24+
boolean isAscending;
25+
26+
// go to index where you find a number different from
27+
// previous number (req. to determine sort order)
28+
for (i = 1; i < a.length; i++) {
29+
if (a[i] != a[i - 1]) break;
30+
}
31+
32+
// all elements equal or only a single element
33+
if (i == a.length) {
34+
return true;
35+
}
36+
37+
// determine sort order of array
38+
if (a[i] > a[i - 1]) {
39+
isAscending = true;
40+
} else {
41+
isAscending = false;
42+
}
43+
44+
// check if appropriate sort property is hold for rest of array
45+
if (isAscending) {
46+
for (; i < a.length; i++) {
47+
if (a[i] < a[i - 1]) return false;
48+
}
49+
} else {
50+
for (; i < a.length; i++) {
51+
if (a[i] > a[i - 1]) return false;
52+
}
53+
}
54+
55+
return true;
56+
}
57+
58+
public static void main(String a[]) {
59+
System.out.println(isSorted(new int[]{1, 2, 3, 4, 5}));
60+
System.out.println(isSorted(new int[]{5, 4, 3, 2, 1}));
61+
System.out.println(isSorted(new int[]{}));
62+
System.out.println(isSorted(new int[]{0}));
63+
System.out.println(isSorted(new int[]{0, 0, 0, 0, 0, 0}));
64+
System.out.println(isSorted(new int[]{4, 7, 9, 1, 0}));
65+
}
66+
}

0 commit comments

Comments
 (0)