forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
29 lines (25 loc) · 771 Bytes
/
BubbleSort.java
File metadata and controls
29 lines (25 loc) · 771 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
import java.util.Arrays;
public class BubbleSort {
private static void bubbleSort(int[] nums) {
boolean hasChange = true;
for (int i = 0, n = nums.length; i < n - 1 && hasChange; ++i) {
hasChange = false;
for (int j = 0; j < n - i - 1; ++j) {
if (nums[j] > nums[j + 1]) {
swap(nums, j, j + 1);
hasChange = true;
}
}
}
}
private static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void main(String[] args) {
int[] nums = {1, 2, 7, 9, 5, 8};
bubbleSort(nums);
System.out.println(Arrays.toString(nums));
}
}