Skip to content

Commit 2c4be94

Browse files
authored
Update Bubble_Sort.java
1 parent 6d19bbf commit 2c4be94

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

Sorting Algorithms/Bubble_Sort.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
1+
/*
2+
Bubble Sort is the simplest sorting algorithm
3+
that works by repeatedly swapping the adjacent
4+
elements if they are in wrong order.
5+
6+
7+
*/
18
public class BubbleSortExample {
29
static void bubbleSort(int[] arr) {
10+
// finding array size.
311
int n = arr.length;
412
int temp = 0;
13+
//each iteration place max element of 1 to n-i index at index n-i
514
for(int i=0; i < n; i++){
615
for(int j=1; j < (n-i); j++){
716
if(arr[j-1] > arr[j]){
@@ -32,3 +41,8 @@ public static void main(String[] args) {
3241

3342
}
3443
}
44+
45+
/*
46+
Bubble Sort always runs O(n^2) time even if the array is sorted.
47+
It can be optimized by stopping the algorithm if inner loop didn’t cause any swap.
48+
*/

0 commit comments

Comments
 (0)