Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b9b06af

Browse files
More Efficient Bubble Sort Code
1 parent d1ea04d commit b9b06af

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

‎java-programs/BubbleSort.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,22 @@
77
public class BubbleSort {
88

99
public void bubbleSort(int[] arr) {
10+
boolean swap;
1011
int n = arr.length;
1112
int tmp = 0;
1213
for (int i = 0; i < n ; i++) {
13-
for (int j = 1; j < n-1; j++) {
14+
swap = false;
15+
for (int j = 1; j < n-i; j++) {
1416
if (arr[j-1] > arr[j]) {
15-
tmp = arr[j - 1];
16-
arr[j-1] = arr[j];
17-
arr[j] = tmp;
17+
tmp = arr[j];
18+
arr[j] = arr[j-1];
19+
arr[j-1] = tmp;
20+
swap = true;
1821
}
1922
}
23+
if (!swap){
24+
break;
25+
}
2026
}
2127
}
2228

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /