Last active
August 29, 2015 14:05
-
-
Save luc99a/89c186186b0eb088ab1e to your computer and use it in GitHub Desktop.
Some sort algorithms written in Python
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
#Bubblesort algorithm | |
#code by luc99a | |
def bubblesort(list): | |
swap_count = -1 | |
while not swap_count == 0: | |
swap_count = 0 | |
for i in range(0, len(list) - 1): | |
if list[i] > list[i + 1]: | |
temp = list[i + 1] | |
list[i + 1] = list[i] | |
list[i] = temp | |
swap_count += 1 | |
return list | |
list = [5, 6, 2, 7, 9, 1, 4, 2, 5, 3] | |
print bubblesort(list) |
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
#Quicksort algorithm | |
#code by luc99a | |
def quicksort(list): | |
if len(list) == 0 or len(list) == 1: | |
return list | |
bigger_list = [] | |
lower_list = [] | |
pivot_index = len(list) / 2 | |
pivot = list[pivot_index] | |
for i in range(0, len(list)): | |
num = list[i] | |
if num > pivot: | |
bigger_list.append(num) | |
elif num <= pivot and i != pivot_index: | |
lower_list.append(num) | |
return quicksort(lower_list) + [pivot] + quicksort(bigger_list) | |
list = [5, 6, 1, 4, 8, 3, 5, 7, 9, 2] | |
print quicksort(list) |
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
#Selectionsort algorithm | |
#code by luc99a | |
def selectionsort(list): | |
swap_index = 0 | |
lowest_index = -1 | |
looped = 0 | |
while not looped == len(list): | |
looped += 1 | |
for i in range(swap_index, len(list)): | |
if i == swap_index: | |
lowest_index = i | |
elif list[i] < list[lowest_index]: | |
lowest_index = i | |
temp = list[lowest_index] | |
list[lowest_index] = list[swap_index] | |
list[swap_index] = temp | |
swap_index += 1 | |
return list | |
list = [5, 2, 6, 4, 7, 8, 3, 9, 0, 4] | |
print selectionsort(list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment