Skip to content

Instantly share code, notes, and snippets.

@brenogcota
Created September 19, 2022 00:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brenogcota/00f82b23a1901dca88cefc4500699317 to your computer and use it in GitHub Desktop.
Save brenogcota/00f82b23a1901dca88cefc4500699317 to your computer and use it in GitHub Desktop.
Bubble Sort example in Javascript and Go

Bubble Sort

Bubble Sort example in Javascript and Go

Javascript

function BubbleSort(array) {
	var swapCount = 1
	while (swapCount > 0) {
		swapCount = 0
		for (let itemIndex = 0; itemIndex < array.length -1; itemIndex++) {
			if (array[itemIndex] > array[itemIndex+1]) {
                let temp = array[itemIndex+1]
                array[itemIndex+1] = array[itemIndex];
                array[itemIndex] = temp;
                
				swapCount += 1
			}
		}
	}
    return array
}

Go

func BubbleSort(array []int) {
	swapCount := 1
	for swapCount > 0 {
		swapCount = 0
		for itemIndex := 0; itemIndex < len(array)-1; itemIndex++ {
			if array[itemIndex] > array[itemIndex+1] {
				array[itemIndex], array[itemIndex+1] = array[itemIndex+1], array[itemIndex]
				swapCount += 1
			}
		}
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment