Exemplo n.º 1
0
// Select will rearrange data so that data[k] is the kth smallest element.
// data[0 .. k-1] <= data[k] <= data[k+1 .. n]
func Select(data sort.Interface, k int) (id int) {
	n := data.Len()
	if k < 0 || k >= n {
		panic("Select with invalid k")
	}
	rand.Shuffle(data)

	lo := 0
	hi := n - 1
	for hi > lo {
		i := Partition(data, lo, hi)
		if i > k {
			hi = i - 1
		} else if i < k {
			lo = i + 1
		} else {
			return i
		}
	}
	return lo
}
Exemplo n.º 2
0
// QuickSort3Way sorts the slice using quicksort with 3way partition.
func QuickSort3Way(data sort.Interface) {
	rand.Shuffle(data)
	quickSort3Way(data, 0, data.Len()-1)
}