From 591dfe1d0946bb36a975dc28f01e37154fa287db Mon Sep 17 00:00:00 2001 From: Gopal0Gupta <114791914+Gopal0Gupta@users.noreply.github.com> Date: Sun, 15 Oct 2023 11:22:33 +0530 Subject: [PATCH] Update BubbleSort.kt --- src/main/kotlin/sort/BubbleSort.kt | 37 ++++++++---------------------- 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/src/main/kotlin/sort/BubbleSort.kt b/src/main/kotlin/sort/BubbleSort.kt index c9bc384..36c1781 100644 --- a/src/main/kotlin/sort/BubbleSort.kt +++ b/src/main/kotlin/sort/BubbleSort.kt @@ -6,37 +6,18 @@ package sort * @param array The array to be sorted * Sorts the array in increasing order * - * Worst-case performance O(n^2) - * Best-case performance O(n) - * Average performance O(n^2) - * Worst-case space complexity O(1) **/ -fun > bubbleSort(array: Array) { - val length = array.size - 1 +fun bubbleSort(arr: IntArray) { + val n = arr.size - for (i in 0..length) { - var isSwapped = false - for (j in 1..length) { - if (array[j] < array[j - 1]) { - isSwapped = true - swapElements(array, j, j - 1) + for (i in 0 until n - 1) { + for (j in 0 until n - i - 1) { + if (arr[j] > arr[j + 1]) { + // Swap the elements + val temp = arr[j] + arr[j] = arr[j + 1] + arr[j + 1] = temp } } - - if (!isSwapped) break - } -} - -/** - * This method swaps the element at two indexes - * - * @param array The array containing the elements - * @param idx1 Index of first element - * @param idx2 Index of second element - * Swaps the element at two indexes - **/ -fun > swapElements(array: Array, idx1: Int, idx2: Int) { - array[idx1] = array[idx2].also { - array[idx2] = array[idx1] } }