Sorting Algorithms

Bubble Sort

Bubble sort is a sorting algorithm that always swaps consecutive elements in the array.

Idea is that bubble sort is done in rounds. After each round, the biggest number is correctly placed at the end of the array.

This seems kind of similar to Insertion Sort, where you swap elements adjacent to each other.

for i in range(len(arr)):
	for j in range(len(arr)-1):
		if arr[j] > arr[j+1]:
			arr[j], arr[j+1] = arr[j+1], arr[j]

C++ implementation

for (int i = 0; i < n; i++) { 
	for (int j = 0; j < n-1; j++) { 
		if (array[j] > array[j+1]) { 
			swap(array[j],array[j+1]); 
		} 
	} 
}