-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBubleSort.java
More file actions
74 lines (59 loc) · 1.39 KB
/
BubleSort.java
File metadata and controls
74 lines (59 loc) · 1.39 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
63
64
65
66
67
68
69
70
71
72
73
74
package sorting;
import java.util.Arrays;
/**
* bubble sort for Integer and String arrays
*
* @time complexity O(n^2)
* @space complexity O(1)
*/
public class BubleSort<T> {
public Object[] unsortedObjectArray;
public Object[] sortedObjectArray;
public void set(T arr) {
this.unsortedObjectArray = (Object[]) arr;
}
public T get() {
if (this.sortedObjectArray != null)
return (T) sortedObjectArray;
return null;
}
public void sort() {
T tmp;
Object[] arr = this.unsortedObjectArray;
for (int i = 0; i < (Arrays.asList((T[]) arr).size()); i++) {
for (int j = 0; j < (Arrays.asList((T[]) arr).size()); j++) {
// System.out.println(Arrays.asList((T[]) arr).get(j));
T a = Arrays.asList((T[]) arr).get(i);
T b = Arrays.asList((T[]) arr).get(j);
if (a instanceof String) {
if (((String) a).compareTo((String) b) < 0) {
tmp = (T) arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
if (a instanceof Integer) {
if (((Integer) a).compareTo((Integer) b) < 0) {
tmp = (T) arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
this.sortedObjectArray = arr;
}
public String display() {
Object[] arr = this.sortedObjectArray;
String out = "[ ";
for (int i = 0; i < arr.length; i++) {
out += arr[i];
if (i == arr.length - 1) {
out += "]";
} else {
out += ", ";
}
}
return out;
}
}