forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortUtils.java
More file actions
62 lines (57 loc) · 1.5 KB
/
SortUtils.java
File metadata and controls
62 lines (57 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.examplehub.utils;
public class SortUtils {
/**
* Test if the array is sorted.
*
* @param array the array to be check.
* @return {@code true} if given array is sorted, otherwise {@code false}.
*/
public static boolean isSorted(int[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i] > array[i + 1]) {
return false;
}
}
return true;
}
/**
* Test if the generic array is sorted.
*
* @param array the array to be checked.
* @param <T> the class of the objects in the array.
* @return {@code true} if given array is sorted, otherwise {@code true}.
*/
public static <T extends Comparable<T>> boolean isSorted(T[] array) {
for (int i = 0; i < array.length - 1; ++i) {
if (array[i].compareTo(array[i + 1]) > 0) {
return false;
}
}
return true;
}
/**
* Swap two elements of array.
*
* @param array the array contains elements
* @param i the first index
* @param j the second index
*/
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
/**
* Swap two elements of array.
*
* @param array the array contains elements
* @param i the first index
* @param j the second index
* @param <T> the class of the objects in the array.
*/
public static <T extends Comparable<T>> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}