Created
January 28, 2012 05:37
-
-
Save liangfu/1692879 to your computer and use it in GitHub Desktop.
general sorting algorithms 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
#!/usr/bin/env python | |
from math import sqrt | |
import random | |
def bubble_sort(a): | |
""" | |
basic sorting method -- bubble sort | |
""" | |
s = len(a) | |
for i in range(0, s): | |
for j in range(i, s): | |
if a[i]>a[j]: | |
a[i], a[j] = a[j], a[i] | |
return a | |
def selection_sort(a): | |
""" | |
select sort - time complexity: O(n^2), | |
out performs 'bubble sort' | |
""" | |
s = len(a) | |
for i in range(0, s): | |
m = i | |
for j in range(i+1, s): | |
if a[j]<a[m]: | |
m = j | |
a[i], a[m] = a[m], a[i] | |
return a | |
def insertion_sort(a): | |
""" | |
insert sort -- time complexity: O(n^2), | |
generally out performs 'select sort' | |
""" | |
s = len(a) | |
for i in range(1, s): | |
for j in range(i-1, -1, -1): | |
if a[j]>a[j+1]: | |
a[j+1], a[j] = a[j], a[j+1] | |
return a | |
def test_sort(): | |
a = range(1, 20) | |
random.shuffle(a) | |
print a | |
print sorted(a) # examin the test result | |
random.shuffle(a) | |
print a | |
print bubble_sort(a) # hand implemented result | |
random.shuffle(a) | |
print a | |
print selection_sort(a) | |
random.shuffle(a) | |
print a | |
print insertion_sort(a) | |
############################################################################# | |
### the main entry | |
############################################################################# | |
def main(): | |
""" | |
The main entry of this program (for testing the functions) | |
""" | |
print 'sort:';test_sort() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment