Skip to content

Commit

Permalink
Improve bubble sort algorithm performance
Browse files Browse the repository at this point in the history
  • Loading branch information
hammadsaedi committed Oct 4, 2023
1 parent e0e346d commit b7fe499
Showing 1 changed file with 14 additions and 8 deletions.
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--;
}
}
}

0 comments on commit b7fe499

Please sign in to comment.