Created
October 26, 2021 22:50
-
-
Save invisiblefunnel/88014de0261eab81b36b3ad9fa2c4c67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be nice to accept
sort.Interfacerather than a concrete type. Hard because the starting value at positionkfor each loop gets swapped before later comparisons that need it.