Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 9 additions & 28 deletions src/main/kotlin/sort/BubbleSort.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 <T : Comparable<T>> bubbleSort(array: Array<T>) {
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 <T : Comparable<T>> swapElements(array: Array<T>, idx1: Int, idx2: Int) {
array[idx1] = array[idx2].also {
array[idx2] = array[idx1]
}
}