用python写算法7[调整数组顺序]

题目:

解法:

维护两个索引,如果第一个指向那个的数字是偶数,第二个指向的数字是奇数,就交换这两个数字

#!/usr/bin/python
#coding=gbk

'''
Created on 2013-03-25
@author: songjian
'''

def adjust_seq(test_arr):
    begin_index = 0
    end_index = len(test_arr) - 1

    while begin_index < end_index:
        if test_arr[begin_index] % 2 == 0:
            while end_index > begin_index:
                print end_index
                if test_arr[end_index] % 2 == 1:
                    test_arr[end_index], test_arr[begin_index] = test_arr[begin_index], test_arr[end_index]
                    break
                end_index -= 1
        begin_index += 1

def main():
    test_case = [5, 3, 2, 4, 1]
    adjust_seq(test_case)
    print test_case

if __name__ == '__main__':
    main()

 

posted on 2013-03-27 15:11  jiyiyouxin  阅读(389)  评论(0)    收藏  举报