From b7fe499d8ad9083d4c614c2f1acc55928b2e140f Mon Sep 17 00:00:00 2001 From: Hammad Saeedi Date: Thu, 5 Oct 2023 03:40:53 +0500 Subject: [PATCH] Improve bubble sort algorithm performance Fixes #196 --- .../java/algorithm/BubbleSortSnippet.java | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/src/main/java/algorithm/BubbleSortSnippet.java b/src/main/java/algorithm/BubbleSortSnippet.java index cac23195..50f81e46 100644 --- a/src/main/java/algorithm/BubbleSortSnippet.java +++ b/src/main/java/algorithm/BubbleSortSnippet.java @@ -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--; } } }