Sorting Algorithms

Bubble Sort

1
def bubble_sort(a):
2
length = len(a)
3
for i in range(0, length):
4
for j in range(0, i):
5
if a[i] < a[j]:
6
a[i], a[j] = a[j], a[i]
Copied!

Selection Sort

1
def selection_sort(a):
2
length = len(a)
3
for i in range(length):
4
min_idx = i
5
for j in range(i, length):
6
if a[j] < a[min_idx]:
7
min_idx = j
8
a[min_idx], a[i] = a[i], a[min_idx]
Copied!

Insertion Sort

1
def insertion_sort(a):
2
length = len(a)
3
for i in range(1, length):
4
key = a[i]
5
j = i - 1
6
while a[j] > key and j >= 0:
7
a[j + 1] = a[j]
8
j -= 1
9
a[j + 1] = key
Copied!

Merge Sort

1
​
Copied!

Quick Sort

1
def quick_sort(a, l, r):
2
if l < r:
3
pos = partition(a, l, r)
4
quick_sort(a, l, pos - 1)
5
quick_sort(a, pos + 1, r)
6
​
7
def partition(a, l, r):
8
pivot = a[r]
9
i = l - 1
10
for j in range(l, r):
11
if a[j] < pivot:
12
i += 1
13
a[j], a[i] = a[i], a[j]
14
a[i + 1], a[r] = a[r], a[i + 1]
15
return i + 1
Copied!

Heap Sort

1
​
Copied!