MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / kthNumber

Function kthNumber

math/kthnumber.go:25–43  ·  view source on GitHub ↗

kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).

(nums []int, k int)

Source from the content-addressed store, hash-verified

23
24// kthNumber use the selection algorithm (based on the partition method - the same one as used in quicksort).
25func 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}

Callers 2

FindKthMaxFunction · 0.85
FindKthMinFunction · 0.85

Calls 1

PartitionFunction · 0.92

Tested by

no test coverage detected