Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated Bubblesort.kt #99

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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]
}
}