前面我们讲解了奇偶排序算法,现在我们用python代码来实现下
#!/usr/bin/python
# -*- coding: utf-8 -*-
#奇偶排序
def odd_even_sort(the_list):
odd_flag = False
even_flag = False
while( (not odd_flag) or (not even_flag)):
even_flag = True
i = 0
while(i < len(the_list)-1):
if the_list[i] > the_list[i+1]:
the_list[i], the_list[i + 1] = the_list[i + 1], the_list[i]
even_flag = False
i += 2
print the_list
odd_flag = True
j = 1
while(j < len(the_list)-1):
if the_list[j] > the_list[j+1]:
the_list[j], the_list[j + 1] = the_list[j + 1], the_list[j]
odd_flag = False
j += 2
print the_list
return the_list
if __name__ == '__main__':
the_list = [10, 12, 7, 5]
print "排序前:" + str(the_list)
print "排序后:" + str(odd_even_sort(the_list))
我们运行下,看结果
排序前:[10, 12, 7, 5]
[10, 12, 7, 5]
[10, 12, 5, 7]
[10, 5, 12, 7]
[5, 10, 12, 7]
[5, 10, 7, 12]
[5, 7, 10, 12]
[5, 7, 10, 12]
[5, 7, 10, 12]
[5, 7, 10, 12]
排序后:[5, 7, 10, 12]
符合预期