- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBubbleSort.java
More file actions
Latest commit
70 lines (52 loc) · 1.75 KB
/
Copy pathBubbleSort.java
File metadata and controls
70 lines (52 loc) · 1.75 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
packageSorting;
importjava.util.Random;
publicclassBubbleSort {
// Sort the array using bubble sort. The idea behind
// bubble sort is to look for adjacent indexes which
// are out of place and interchange their elements
// until the entire array is sorted.
publicstaticvoidbubbleSort(finalint[] ar) {
if (ar == null)
return;
finalintN = ar.length;
booleansorted;
do {
sorted = true;
for (inti = 1; i < N; i++) {
if (ar[i] < ar[i - 1]) {
swap(ar, i - 1, i);
sorted = false;
}
}
} while (!sorted);
}
privatestaticvoidswap(finalint[] ar, finalinti, finalintj) {
finalinttmp = ar[i];
ar[i] = ar[j];
ar[j] = tmp;
}
publicstaticvoidmain(finalString[] args) {
finalint[] array = { 10, 4, 6, 8, 13, 2, 3 };
bubbleSort(array);
System.out.println(java.util.Arrays.toString(array));
// TODO(williamfiset): move to javatests/...
runTests();
}
staticRandomRANDOM = newRandom();
publicstaticvoidrunTests() {
finalintNUM_TESTS = 1000;
for (inti = 1; i <= NUM_TESTS; i++) {
finalint[] array = newint[i];
for (intj = 0; j < i; j++)
array[j] = randInt(-1000000, +1000000);
finalint[] arrayCopy = array.clone();
bubbleSort(array);
java.util.Arrays.sort(arrayCopy);
if (!java.util.Arrays.equals(array, arrayCopy))
System.out.println("ERROR");
}
}
staticintrandInt(finalintmin, finalintmax) {
returnRANDOM.nextInt((max - min) + 1) + min;
}
}