diff --git a/src/main/java/algorithm/BubbleSortSnippet.java b/src/main/java/algorithm/BubbleSortSnippet.java index cac23195..faecc94d 100644 --- a/src/main/java/algorithm/BubbleSortSnippet.java +++ b/src/main/java/algorithm/BubbleSortSnippet.java @@ -22,29 +22,35 @@ * SOFTWARE. */ -package algorithm; + package algorithm; -/** - * BubbleSortSnippet. - */ -public class BubbleSortSnippet { - - /** - * Sort an array with bubbleSort algorithm. - * - * @param arr array to sort - */ - public static void bubbleSort(int[] arr) { - var lastIndex = arr.length - 1; - - 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; - } - } - } - } -} + /** + * BubbleSortSnippet. + */ + public class BubbleSortSnippet { + + /** + * Sort an array using the bubble sort algorithm. + * + * @param arr array to sort + */ + public static void bubbleSort(int[] arr) { + int lastIndex = arr.length - 1; + boolean sorted; + + do { + sorted = true; + for (int i = 0; i < lastIndex; i++) { + if (arr[i] > arr[i + 1]) { + int tmp = arr[i]; + arr[i] = arr[i + 1]; + arr[i + 1] = tmp; + sorted = false; + } + } + + lastIndex--; + + } while (!sorted); + } + } \ No newline at end of file