Skip to content

Commit 2813e11

Browse files
authored
Merge pull request #785 from shiv2711/patch-1
Add Bubble_Sort.java
2 parents 00776fd + 2c4be94 commit 2813e11

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Sorting Algorithms/Bubble_Sort.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
*/
8+
public class BubbleSortExample {
9+
static void bubbleSort(int[] arr) {
10+
// finding array size.
11+
int n = arr.length;
12+
int temp = 0;
13+
//each iteration place max element of 1 to n-i index at index n-i
14+
for(int i=0; i < n; i++){
15+
for(int j=1; j < (n-i); j++){
16+
if(arr[j-1] > arr[j]){
17+
//swap elements
18+
temp = arr[j-1];
19+
arr[j-1] = arr[j];
20+
arr[j] = temp;
21+
}
22+
}
23+
}
24+
25+
}
26+
public static void main(String[] args) {
27+
int arr[] ={3,60,35,2,45,320,5};
28+
29+
System.out.println("Array Before Bubble Sort");
30+
for(int i=0; i < arr.length; i++){
31+
System.out.print(arr[i] + " ");
32+
}
33+
System.out.println();
34+
35+
bubbleSort(arr);//sorting array elements using bubble sort
36+
37+
System.out.println("Array After Bubble Sort");
38+
for(int i=0; i < arr.length; i++){
39+
System.out.print(arr[i] + " ");
40+
}
41+
42+
}
43+
}
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)