Skip to content

Commit b97ebba

Browse files
bubble-sort solution
1 parent a31d0d9 commit b97ebba

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

src/main/java/org/example/Main.java

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,33 @@
11
package org.example;
22

3+
import java.util.Arrays;
4+
35
public class Main {
6+
7+
/* Bubble sort is a type of sorting algorithm we can use to arrange a set of values in ascending order.
8+
A real-world example is how the contact list on our phones is sorted in alphabetical order.
9+
This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high. */
10+
411
public static void main(String[] args) {
12+
int[] data = {10, -2, 0, 100, -7, 15};
13+
bubbleSort(data);
14+
System.out.println(Arrays.toString(data));
15+
}
516

17+
static void bubbleSort(int[] array) {
18+
int size = array.length;
19+
// loop over each element of the array to access them
20+
for (int i = 0; i < size - 1; i++) {
21+
// loop to compare array elements
22+
for (int j = 0; j < size - i - 1; j++) {
23+
// to compare two adjacent elements in the array: "<" - DESC order, ">" - ASC order
24+
if (array[j] > array[j + 1]) {
25+
// swapping will occur if elements aren't in the intended order
26+
int temp = array[j];
27+
array[j] = array[j + 1];
28+
array[j + 1] = temp;
29+
}
30+
}
31+
}
632
}
7-
}
33+
}

0 commit comments

Comments
 (0)