Bubble Sort - Insight7/go_algo GitHub Wiki

Bubble sort

Bubble sort is the simplest sorting algorithm.

It is in-place sorting algorithm means it does the sorting in the given array only.

The idea is to repeatedly sort all adjacent element by swapping them in correct order until you have a completely sorted array.

for i := 0; i < n-1; i++ {

	isSwappingDone = false
	for j := 0; j < n-i-1; j++ {
		if array[j] > array[j+1] {
			Swap(&array[j], &array[j+1])
			isSwappingDone = true
		}
	}
	if !isSwappingDone {
		break
	}
}

One more interesting function here is the Swap function. We have various method to swap.

Swapping two values

Simplest one

func Swap(a *int, b *int) {
	temp := *a
	*a = *b
	*b = temp
}

Without using the temp variable

a = a^b
b = a^b
a = a^b

Similar approach can be taken with / * and + -

The issue here is we cannot divide with zero and + - can lead to buffer overflow

The XOR will also fail when a=b

Complexity

Worst case : O(n2)

Best case : O(n)

Space : O(1)

In-place : Yes

Links

Tutorial point wiki link

swap without temp variable

⚠️ **GitHub.com Fallback** ⚠️