From 454c8bc3c475920e4b3161981bd0d76d564b9cf3 Mon Sep 17 00:00:00 2001 From: William Crum Date: Sun, 20 Jun 2021 18:23:38 -0700 Subject: [PATCH] Create bubble_sort.md Python version of https://www.30secondsofcode.org/js/s/bubble-sort --- snippets/bubble_sort.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 snippets/bubble_sort.md diff --git a/snippets/bubble_sort.md b/snippets/bubble_sort.md new file mode 100644 index 000000000..a682e8f88 --- /dev/null +++ b/snippets/bubble_sort.md @@ -0,0 +1,23 @@ +--- +title: bubble_sort +tags: algorithm,array,beginner +firstSeen: 2021-06-21T00:52:09+17:00 +--- + +Sorts an array of numbers, using the bubble sort algorithm. + +- Use a `for` loop to iterate over the elements of the passed array, terminating before the last element. +- Use a nested `for` loop to iterate over the segment of the array between `0` and `len(a) - i - 1`, swapping any adjacent out of order elements. + +```python +def bubble_sort(a): + for i in range(len(a)): + for j in range(len(a) - i - 1): + if a[j + 1] < a[j]: + a[j], a[j + 1] = a[j + 1], a[j] + return a +``` + +```python +bubble_sort([2, 1, 4, 3]) # [1, 2, 3, 4] +```