From 8881e9aa4e43c8c437d827882dccc9d1b2a92b1f Mon Sep 17 00:00:00 2001 From: shellhub Date: Thu, 26 Sep 2019 10:02:58 +0800 Subject: [PATCH] make code more readable --- Sorts/BubbleSort.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/Sorts/BubbleSort.java b/Sorts/BubbleSort.java index edad5e354..29d588932 100644 --- a/Sorts/BubbleSort.java +++ b/Sorts/BubbleSort.java @@ -18,18 +18,15 @@ class BubbleSort implements SortAlgorithm { @Override public > T[] sort(T array[]) { - int last = array.length; - //Sorting - boolean swap; - do { - swap = false; - for (int count = 0; count < last - 1; count++) { - if (less(array[count], array[count + 1])) { - swap = swap(array, count, count + 1); - } + for (int i = 0, size = array.length; i < size - 1; ++i) { + boolean swapped = false; + for (int j = 0; j < size - 1 - i; ++j) { + swapped = less(array[j], array[j + 1]) && swap(array, j, j + 1); } - last--; - } while (swap); + if (!swapped) { + break; + } + } return array; }