Skip to content

Commit f405669

Browse files
author
Farheen Shabbir Shaikh
committed
Add Bubble Sort algorithm with comments
1 parent 7602f1e commit f405669

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Sorting/BubbleSort.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* BubbleSort.java
3+
* This program implements the Bubble Sort algorithm.
4+
* Time Complexity: O(n^2)
5+
*/
6+
7+
public class BubbleSort {
8+
9+
public static void bubbleSort(int[] arr) {
10+
int n = arr.length;
11+
boolean swapped;
12+
for (int i = 0; i < n - 1; i++) {
13+
swapped = false;
14+
15+
for (int j = 0; j < n - i - 1; j++) {
16+
if (arr[j] > arr[j + 1]) {
17+
// swap arr[j] and arr[j+1]
18+
int temp = arr[j];
19+
arr[j] = arr[j + 1];
20+
arr[j + 1] = temp;
21+
22+
swapped = true;
23+
}
24+
}
25+
26+
// If no two elements were swapped, array is sorted
27+
if (!swapped)
28+
break;
29+
}
30+
}
31+
32+
public static void main(String[] args) {
33+
int[] arr = {64, 25, 12, 22, 11};
34+
bubbleSort(arr);
35+
System.out.println("Sorted array:");
36+
for (int num : arr) {
37+
System.out.print(num + " ");
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)