Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve bubble sort algorithm performance #197

Closed
wants to merge 4 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/main/java/algorithm/BubbleSortSnippet.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,22 @@ public class BubbleSortSnippet {
* @param arr array to sort
*/
public static void bubbleSort(int[] arr) {
var lastIndex = arr.length - 1;
int lastIndex = arr.length - 1;
boolean swapped = true;

for (var j = 0; j < lastIndex; j++) {
for (var i = 0; i < lastIndex - j; i++) {
if (arr[i] > arr[i + 1]) {
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
while (swapped) {
swapped = false;

for (int i = 0; i < lastIndex; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}

lastIndex--;
}
}
}