Python学习之---冒泡,选择,插入排序

最近学习了python基础,写一下3大排序练练手:

 1 '''

 2 Created on 2013-8-23

 3 

 4 @author: codegeek

 5 '''

 6 

 7 def bubble_sort(seq):

 8     for i in range(len(seq)):

 9         for j in range(i,len(seq)):

10             if seq[j] < seq[i]:

11                 tmp = seq[j]

12                 seq[j] = seq[i]

13                 seq[i] = tmp

14                 

15 def selection_sort(seq):

16     for i in range(len(seq)):

17         position = i

18         for j in range(i,len(seq)):

19             if seq[position] > seq[j]:

20                 position = j

21         if position != i:

22                 tmp = seq[position]

23                 seq[position] = seq[i]

24                 seq[i] = tmp

25 

26 def insertion_sort(seq):

27     if len(seq) > 1:

28         for i in range(1,len(seq)):

29             while i > 0 and seq[i] < seq[i-1]:

30                 tmp = seq[i]

31                 seq[i] = seq[i-1]

32                 seq[i-1] = tmp

33                 i = i - 1

34                 

35 if __name__ == "__main__":

36     print "--------bubble_sort-------------"

37     seq = [22,1,33,4,7,6,8,9,11]

38     bubble_sort(seq)

39     print seq

40     print "--------selection_sort-------------"

41     seq = [88,44,33,4,7,6,8,9,11]

42     selection_sort(seq)

43     print seq

44     print "--------insertion_sort-------------"

45     seq = [777,44,33,4,7,6,1111,100,11]

46     insertion_sort(seq)

47     print seq

48     

 

你可能感兴趣的:(python)