-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
82 lines (72 loc) · 1.82 KB
/
Copy pathBubbleSort.java
File metadata and controls
82 lines (72 loc) · 1.82 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
75
76
77
78
79
80
81
82
public class BubbleSort {
public static void bubbleSort(int[] array) {
int n = array.length; // n is a length of array.
// 0th index based
/*for (int turn = 0; turn < n - 1; turn++) {
for (int j = 0; j < n - 1 - turn; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}*/
// 1th index based
/*for (int turn = 1; turn <= n - 1; turn++) {
for (int j = 0; j <= n - 1 - turn; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}*/
// The time complexity of these two method is O(n²).
/*boolean swaped = false;
int swapping = 0;
int cout = 0;
for (int turn = 0; turn < n - 1; turn++) {
for (int j = 0; j < n - 1 - turn; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swaped = true;
swapping++;
}
cout++;
}
System.out.println("count of How many times loop iterates = " + cout);
System.out.println("Count of how many times number is swapped = " + swapping);
if (swaped == false) {
break;
}
}*/
//Most ideal and best code :)
boolean swaped = false;
for (int turn = 0; turn < n - 1; turn++) {
for (int j = 0; j < n - 1 - turn; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
swaped = true;
}
}
if (swaped == false) {
break;
}
}
// The time complexity of this method is O(n).
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] sadoxer) {
int[] array = {1, 2, 3, 4, 5};
bubbleSort(array);
printArray(array);
}
}