Skip to content

Commit 321b065

Browse files
Merge pull request #208 from Taranpreet1407/blackboxai/add-bubble-sort
Add BubbleSort.java with bubble sort algorithm implementation
2 parents b968400 + 9284580 commit 321b065

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.Scanner;
2+
3+
public class BubbleSort {
4+
5+
public static int[] arrInput(Scanner sc) {
6+
System.out.print("Enter the size of the array: ");
7+
int n = sc.nextInt();
8+
int[] arr = new int[n];
9+
System.out.println("Enter the elements of the array: ");
10+
for (int i = 0; i < n; i++) {
11+
arr[i] = sc.nextInt();
12+
}
13+
return arr;
14+
}
15+
16+
public static void bubbleSort(int[] arr) {
17+
int n = arr.length;
18+
for (int i = 0; i < n - 1; i++) {
19+
for (int j = 0; j < n - i - 1; j++) {
20+
if (arr[j] > arr[j + 1]) {
21+
// swap arr[j] and arr[j+1]
22+
int temp = arr[j];
23+
arr[j] = arr[j + 1];
24+
arr[j + 1] = temp;
25+
}
26+
}
27+
}
28+
}
29+
30+
public static void main(String[] args) {
31+
Scanner sc = new Scanner(System.in);
32+
33+
int[] arr = arrInput(sc);
34+
35+
System.out.print("Array before sorting: ");
36+
for (int num : arr) {
37+
System.out.print(num + " ");
38+
}
39+
System.out.println();
40+
41+
bubbleSort(arr);
42+
43+
System.out.print("Array after sorting: ");
44+
for (int num : arr) {
45+
System.out.print(num + " ");
46+
}
47+
System.out.println();
48+
49+
sc.close();
50+
}
51+
}

0 commit comments

Comments
 (0)