Skip to content

Instantly share code, notes, and snippets.

@invisiblefunnel
Created October 26, 2021 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save invisiblefunnel/88014de0261eab81b36b3ad9fa2c4c67 to your computer and use it in GitHub Desktop.
Save invisiblefunnel/88014de0261eab81b36b3ad9fa2c4c67 to your computer and use it in GitHub Desktop.
package quickselect
func Quickselect(data []int, k, left, right int) {
var t, i, j int
for right > left {
t = data[k]
i = left
j = right
swap(data, left, k)
if compare(data[right], t) > 0 {
swap(data, left, right)
}
for i < j {
swap(data, i, j)
i++
j--
for compare(data[i], t) < 0 {
i++
}
for compare(data[j], t) > 0 {
j--
}
}
if compare(data[left], t) == 0 {
swap(data, left, j)
} else {
j++
swap(data, j, right)
}
if j <= k {
left = j + 1
}
if k <= j {
right = j - 1
}
}
}
func swap(data []int, i, j int) {
data[i], data[j] = data[j], data[i]
}
func compare(a, b int) int {
if a < b {
return -1
}
if b < a {
return 1
}
return 0
}
@invisiblefunnel
Copy link
Author

Would be nice to accept sort.Interface rather than a concrete type. Hard because the starting value at position k for each loop gets swapped before later comparisons that need it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment