From 3a64d7af673324cff8a24bee3b3556cdcc70cd9f Mon Sep 17 00:00:00 2001 From: Hammad Saeedi Date: Mon, 16 Oct 2023 21:51:37 +0500 Subject: [PATCH] bubble sort: same as before --- .../java/algorithm/BubbleSortSnippet.java | 70 +++++++++---------- 1 file changed, 32 insertions(+), 38 deletions(-) diff --git a/src/main/java/algorithm/BubbleSortSnippet.java b/src/main/java/algorithm/BubbleSortSnippet.java index 599b2536..8785e1e2 100644 --- a/src/main/java/algorithm/BubbleSortSnippet.java +++ b/src/main/java/algorithm/BubbleSortSnippet.java @@ -1,11 +1,11 @@ /* -* MIT License -* -* Copyright (c) 2017-2023 Ilkka Seppälä -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights + * MIT License + * + * Copyright (c) 2017-2022 Ilkka Seppälä + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: @@ -22,35 +22,29 @@ * SOFTWARE. */ -package algorithm; - -/** - * BubbleSortSnippet. - */ -public class BubbleSortSnippet { - - /** - * Sort an array with bubbleSort algorithm. - * - * @param arr array to sort - */ - public static void bubbleSort(int[] arr) { - int lastIndex = arr.length - 1; - boolean swapped = true; - - while (swapped) { - swapped = false; + package algorithm; - 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--; - } - } -} + /** + * 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; + } + } + } + } + } \ No newline at end of file