-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.java
More file actions
38 lines (30 loc) · 935 Bytes
/
BubbleSort.java
File metadata and controls
38 lines (30 loc) · 935 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
32
33
34
35
36
37
38
package basicsortingalgorithms;
public class BubbleSort {
public static void sort(int[] nums) {
for (int turn = 0; turn < nums.length - 1; turn++) {
boolean swapped = false;
for (int j = 0; j < nums.length - 1 - turn; j++) {
if ( nums[j] > nums[j + 1]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void printArray(int[] nums) {
for (int i = 0; i < nums.length; i++) {
System.out.print(nums[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int nums[] = {5, 4, 1, 3, 2};
// int nums[] = {1, 2, 3, 4, 5};
sort(nums);
printArray(nums);
}
}
// Bubble sort