find the kth smallest number in a list in go

Here's a code snippet to find the kth smallest number in a list using binary search in Go:

main.go
func findKthSmallest(arr []int, k int) int {
  n := len(arr)
  left, right := 0, n-1
  for left <= right {
    pivotIndex := partition(arr, left, right)
    if pivotIndex == k-1 {
      return arr[pivotIndex]
    } else if pivotIndex > k-1 {
      right = pivotIndex - 1
    } else {
      left = pivotIndex + 1
    }
  }
  return -1
}

func partition(arr []int, left, right int) int {
  pivotIndex := left
  for i := left; i < right; i++ {
    if arr[i] < arr[right] {
      arr[i], arr[pivotIndex] = arr[pivotIndex], arr[i]
      pivotIndex++
    }
  }
  arr[pivotIndex], arr[right] = arr[right], arr[pivotIndex]
  return pivotIndex
}
637 chars
28 lines

To use this function, you can pass in the list of integers and the value k, and it will return the kth smallest number. The partition function is a helper function that partitions the list around a pivot value and returns the index of the pivot. The findKthSmallest function uses binary search to find the kth smallest number by repeatedly partitioning the list until the pivot is at index k-1.

gistlibby LogSnag