Created
February 5, 2017 13:57
-
-
Save vskrachkov/be742b4bcd178e731cb1c32213113387 to your computer and use it in GitHub Desktop.
Examples of bible sort, selection sort, insertion sort and merging sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def bubble_sort(a_list): | |
"""Realizes a bubble sort algorithm. | |
Time complexity: O(n^2) | |
""" | |
for one_pass in range(len(a_list)-1): | |
for i in range(len(a_list)-1): | |
if a_list[i] > a_list[i+1]: | |
a_list[i], a_list[i+1] = a_list[i+1], a_list[i] | |
return a_list | |
def selection_sort(a_list): | |
"""Realizes a selection sort algorithm. | |
Time complexity: O(n^2) | |
""" | |
for one_pass in range(len(a_list)-1, 0, -1): | |
position_of_max = 0 | |
for i in range(1, one_pass+1): | |
if a_list[i] > a_list[position_of_max]: | |
position_of_max = i | |
(a_list[one_pass], | |
a_list[position_of_max]) = a_list[position_of_max], a_list[one_pass] | |
return a_list | |
def insertion_sort(a_list): | |
"""Realized an insertion sort algorithm. | |
Time complexity: O(n^2) | |
""" | |
for i in range(1, len(a_list)): | |
current = a_list[i] | |
position = i | |
while position > 0 and a_list[position-1] > current: | |
a_list[position] = a_list[position-1] | |
position -= 1 | |
a_list[position] = current | |
return a_list | |
def merging_sort(a_list): | |
"""Realized a merged sort algorithm. | |
Time complexity: O(n*log(n)) | |
""" | |
def func(a_list): | |
middle = len(a_list) // 2 | |
if middle: | |
left = a_list[:middle] | |
right = a_list[middle:] | |
func(left) | |
func(right) | |
i = k = j = 0 | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
a_list[k] = left[i] | |
i += 1 | |
else: | |
a_list[k] = right[j] | |
j += 1 | |
k += 1 | |
while i < len(left): | |
a_list[k] = left[i] | |
i += 1 | |
k += 1 | |
while j < len(right): | |
a_list[k] = right[j] | |
j += 1 | |
k += 1 | |
func(a_list) | |
return a_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment