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] } }