Skip to content

Instantly share code, notes, and snippets.

@RomarQ
Last active June 1, 2022 18:10
Show Gist options
  • Save RomarQ/72e4150babdc67a9666ab134f220f84c to your computer and use it in GitHub Desktop.
Save RomarQ/72e4150babdc67a9666ab134f220f84c to your computer and use it in GitHub Desktop.
Go Cheat Sheet

Go Cheat Sheet

Get map keys

func GetMapKeys[K comparable, V any](m map[K]V) []K {
	keys := make([]K, 0)

	for k := range m {
		keys = append(keys, k)
	}

	return keys
}

Bubble sort

func BubbleSort[T int | string](list []T) []T {
	sortedList := make([]T, len(list))
	// Clone list
	for idx, el := range list {
		sortedList[idx] = el
	}

	// Sort list
	for range sortedList {
		for idx, el := range sortedList[1:] {
			if sortedList[idx] > el {
				sortedList[idx+1] = sortedList[idx]
				sortedList[idx] = el
			}
		}
	}

	return sortedList
}

Merge sort

func MergeSort(list []int) []int {
	if length := len(list); length > 1 {
		middle := length / 2
		return merge(mergeSort(list[0:middle]), mergeSort(list[middle:length]))
	}

	return list
}

func merge(left []int, right []int) []int {
	sortedList := make([]int, 0)

	for len(left) > 0 && len(right) > 0 {
		if left[0] > right[0] {
			sortedList = append(sortedList, right[0])
			right = right[1:]
		} else {
			sortedList = append(sortedList, left[0])
			left = left[1:]
		}
	}

	return append(sortedList, append(left, right...)...)
}

Quicksort (Hoare partition scheme)

func quickSort(list []int) {
	if len(list) > 1 {
		p := partition(list)
		quickSort(list[:p])
		quickSort(list[p:])
	}
}

func partition(list []int) int {
	left, right := 0, len(list)-1
	pivot := list[len(list)/2]

	for {
		for list[left] < pivot {
			left += 1
		}
		for list[right] > pivot {
			right -= 1
		}

		if left >= right {
			return right
		}

		aux := list[right]
		list[right] = list[left]
		list[left] = aux
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment