ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bubble Sort Implementation

Python

Goal -- WPM

Ready
Exercise Algorithm Area
1def bubble_sort(arr):
2n = len(arr)
3# Traverse through all array elements
4for i in range(n):
5# Last i elements are already in place
6swapped = False
7for j in range(0, n - i - 1):
8# Traverse the array from 0 to n-i-1
9# Swap if the element found is greater than the next element
10if arr[j] > arr[j + 1]:
11arr[j], arr[j + 1] = arr[j + 1], arr[j]
12swapped = True
13# If no two elements were swapped by inner loop, then break
14if not swapped:
15break
16return arr
Algorithm description viewbox

Bubble Sort Implementation

Algorithm description:

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. It's often used for educational purposes due to its simplicity.

Algorithm explanation:

Bubble Sort works by repeatedly stepping through the list, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The time complexity is O(n^2) in the worst and average cases, and O(n) in the best case (already sorted list). Space complexity is O(1) as it sorts in-place. Edge cases include empty lists or lists with one element, which are handled by the loop conditions.

Pseudocode:

function bubbleSort(array):
  n = length of array
  for i from 0 to n-1:
    swapped = false
    for j from 0 to n-i-2:
      if array[j] > array[j+1]:
        swap array[j] and array[j+1]
        swapped = true
    if not swapped:
      break
  return array