-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble.java
More file actions
39 lines (33 loc) · 1.06 KB
/
bubble.java
File metadata and controls
39 lines (33 loc) · 1.06 KB
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
32
33
34
35
36
37
38
39
public class BubbleSort {
/**
* Standard Bubble Sort algorithm
* @param arr - The unsorted array
*/
public static void sort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Last i elements are already in place
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap adjacent elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// Optimization: If no two elements were swapped by inner loop, then break
if (!swapped) break;
}
}
public static void main(String[] args) {
int[] data = {64, 34, 25, 12, 22, 11, 90};
sort(data);
System.out.println("Sorted array:");
for (int val : data) {
System.out.print(val + " ");
}
}
}