Skip to content

Commit 89837cc

Browse files
Create BubbleSort.java
Implementation of bubble sort algorithm.
1 parent 7f1df0c commit 89837cc

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

BubbleSort.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.Scanner;
2+
3+
public class BubbleSort {
4+
public static void main(String[] args) {
5+
Scanner sc = new Scanner(System.in);
6+
int n = sc.nextInt();
7+
int[] arr = new int[n];
8+
for (int i = 0; i < n; i++)
9+
arr[i] = sc.nextInt();
10+
bubble(arr);
11+
for (int i : arr) {
12+
System.out.print(i + " ");
13+
}
14+
sc.close();
15+
}
16+
17+
public static void bubble(int[] arr) {
18+
for (int i = 1; i <= arr.length - 1; i++)
19+
for (int j = 0; j < arr.length - i; j++)
20+
if (isSmaller(arr, j + 1, j))
21+
swap(arr, j + 1, j);
22+
}
23+
24+
public static boolean isSmaller(int[] arr, int i, int j) {
25+
System.out.println("Comparing " + arr[i] + " with " + arr[j]);
26+
if (arr[i] < arr[j])
27+
return true;
28+
else
29+
return false;
30+
}
31+
32+
public static void swap(int[] arr, int i, int j) {
33+
System.out.println("Swapping " + arr[i] + " and " + arr[j]);
34+
int temp = arr[i];
35+
arr[i] = arr[j];
36+
arr[j] = temp;
37+
}
38+
}

0 commit comments

Comments
 (0)