Skip to content

Commit 28eafde

Browse files
committed
Add BubbleSort algorithm
1 parent 211c28b commit 28eafde

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed
Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
package com.thealgorithms.sorting;
2-
32
public class BubbleSort {
3+
44
public static void bubbleSort(int[] arr) {
55
int n = arr.length;
6+
boolean swapped;
67
for (int i = 0; i < n - 1; i++) {
7-
for (int j = 0; j < n - i - 1; j++) {
8+
swapped = false;
9+
for (int j = 0; j < n - 1 - i; j++) {
810
if (arr[j] > arr[j + 1]) {
11+
// swap
912
int temp = arr[j];
1013
arr[j] = arr[j + 1];
1114
arr[j + 1] = temp;
15+
swapped = true;
1216
}
1317
}
18+
if (!swapped) break;
1419
}
1520
}
1621
}

0 commit comments

Comments
 (0)