kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).
(nums []int, k int)
| 23 | |
| 24 | // kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort). |
| 25 | func kthNumber(nums []int, k int) (int, error) { |
| 26 | if k < 0 || k >= len(nums) { |
| 27 | return -1, search.ErrNotFound |
| 28 | } |
| 29 | start := 0 |
| 30 | end := len(nums) - 1 |
| 31 | for start <= end { |
| 32 | pivot := sort.Partition(nums, start, end) |
| 33 | if k == pivot { |
| 34 | return nums[pivot], nil |
| 35 | } |
| 36 | if k > pivot { |
| 37 | start = pivot + 1 |
| 38 | continue |
| 39 | } |
| 40 | end = pivot - 1 |
| 41 | } |
| 42 | return -1, search.ErrNotFound |
| 43 | } |
no test coverage detected