-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
53 lines (43 loc) · 1.45 KB
/
BubbleSort.java
File metadata and controls
53 lines (43 loc) · 1.45 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
package SortAlgorithms;
import java.util.Arrays;
public class BubbleSort {
public static void main(String... args) {
int[] rightToLef = {35, 45, -50, 12, 18};
int[] leftToRight = {35, 45, -50, 12, 18};
//Bubble sort reading right to left
for (int lastUnsortedIndex = rightToLef.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex; i++) {
if (rightToLef[i] > rightToLef[i + 1]) { //Here you determine ascending or descending
swap(rightToLef, i, i + 1);
}
}
}
System.out.println(Arrays.toString(rightToLef));
//Bubble sort reading left to right
for (int firstIndex = 0; firstIndex < leftToRight.length - 1; firstIndex++) {
for (int i = leftToRight.length - 1; i > firstIndex; i--) {
if (leftToRight[i] > leftToRight[i - 1]) {
swap(leftToRight, i, i - 1);
}
}
}
System.out.println(Arrays.toString(leftToRight));
}
/**
* O(n²) because is into two loops
*
* @param array
* @param i
* @param j
*/
public static void swap(int[] array, int i, int j) {
if (i == j) {
//You shouldn't swap it
return;
}
//Swapping
int temp = array[i]; // O(n)
array[i] = array[j];
array[j] = temp;
}
}