Пример #1
0
func HeapSort(arr *array.List) {
	fmt.Print("before heapsort: ")
	arr.Print()
	heap := heap.New(arr)
	for i := heap.Size(); i > 0; i-- {
		heap.Swap(0, i)
		heap.Heapify(0, i)
	}
	fmt.Print("after heapsort: ")
	arr.Print()
}
Пример #2
0
func QuickSort(arr *array.List, left int, right int, fn SelectPivot) {
	if (right - left) <= 0 {
		return
	}

	pvt := fn(left, right)
	if pvt != right {
		arr.Swap(pvt, right)
	}

	divider := Partition(arr, left, right)
	QuickSort(arr, left, divider-1, fn)
	QuickSort(arr, divider+1, right, fn)
}
Пример #3
0
func Partition(arr *array.List, left, right int) int {
	i := left - 1
	j := i + 1
	for j < right {
		if ret, _ := arr.Compare(j, right); ret < 0 {
			i += 1
			arr.Swap(i, j)
			j += 1
		} else {
			j += 1
		}
	}
	arr.Swap(right, i+1)
	return i + 1
}
Пример #4
0
func Merge(arr *array.List, left int, mid int, right int) {
	i := left
	j := mid + 1
	t := 0
	temp := make([]interface{}, right-left+1)
	for i <= mid && j <= right {
		res, err := arr.Compare(i, j)
		if err != nil {
			panic(fmt.Sprintf("error in compare: %v, index i: %d, index j: %d", err.Error(), i, j))
		}
		if res < 0 {
			temp[t], _ = arr.Get(i)
			i += 1
		} else {
			temp[t], _ = arr.Get(j)
			j += 1
		}
		t += 1
	}

	for i <= mid {
		temp[t], _ = arr.Get(i)
		i += 1
		t += 1
	}

	for j <= right {
		temp[t], _ = arr.Get(j)
		j += 1
		t += 1
	}

	arr.CopyRange(left, temp)
}