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

Bubble sort #27

Open
ghost opened this issue Aug 7, 2022 · 0 comments
Open

Bubble sort #27

ghost opened this issue Aug 7, 2022 · 0 comments

Comments

@ghost
Copy link

ghost commented Aug 7, 2022

// Time Complexity O(n^2)
// Space Complexity O(1)

fun sort(arr: Array): Array {
var items = arr.copyOf()
for (i in 0 .. items.size - 1) {
for (j in i + 1 .. items.size - 1) {
if (items[j] < items[i]) {
val tmp = items[j]
items[j] = items[i]
items[i] = tmp
}
}
}
return items;
}

var items = arrayOf(4, 1, 5, 3, 2)

val sortItems = sort(items)
// sortItems is {1, 2, 3, 4, 5}
sortItems.forEach { print("$it ") }
println()

// *** simplified speed test ***
items = Array(200, {0})
.mapIndexed { i, _ -> i }
.toTypedArray()
val tmp = items[5]
items[5] = items[6]
items[6] = tmp
val count = 10000
val start = Date()

for (i in 0..count - 1) {
sort(items)
}

val milliseconds = Date().time - start.time

println(milliseconds)
// about 2742 milliseconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

0 participants