-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubble_Sort.java
More file actions
31 lines (29 loc) · 998 Bytes
/
Copy pathBubble_Sort.java
File metadata and controls
31 lines (29 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.devi;
import java.util.Arrays;
public class Bubble_Sort {
public static void main(String[] args) {
int[] arr = {3,1,5,4,2};
bubble(arr);
System.out.println(Arrays.toString(arr));
}
static void bubble(int[] arr) {
// run the steps n-1 times
for (int i = 0; i <= arr.length-1; i++) {
boolean swapped = false;
// for each step, max item will come at the last respective index
for (int j = 1; j <= arr.length - i - 1; j++) {
// swap if the item is smaller than the previous item
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
swapped = true;
}
}
// if you did not swap for a particular vaue of i, it means the array is sorted
if (!swapped) {
break;
}
}
}
}