荷兰国旗问题

算法(1)——荷兰国旗问题&随机快排

问题描述

  • 荷兰国旗问题用数组的形式的描述:
            给定一个整数数组,从数组中挑选出一个K,要求把数组中小于K的元素放到数组的左边,大于K的元素放到数组的右边,等于K的元素放到数组的中间,最终返回
            例如,给定数组:[2, 3, 1, 9, 7, 6, 1, 4, 5],给定一个值4,那么经过处理原数组可能得一种情况是:[2, 3, 1, 1, 4, 9, 7, 6, 5],需要注意的是,小于4的部分不需要有序,大于4的部分也不需要有序
def newtherlandsSort(list):
    less,more = -1,len(list)    #[0,less]是小于flag的数组,[more,len(list)-1]是大于flag的数组
    current = 0                 #游动的指针,遍历所有数
    flag = list[len(list) - 1]  #取最后一个数为flag
    while True:
        if current == more or current == len(list) - 1:
            list[current], list[len(list) - 1] = list[len(list) - 1], list[current]
            return list
        else:
            if list[current] < flag:
                less += 1
                list[current], list[0 + less] = list[0 + less], list[current]
                current += 1
            elif list[current] == flag:
                current += 1
            elif list[current] > flag:
                more -= 1
                list[current], list[more] = list[more], list[current]

import random
def listCreater():
    list = []
    for _ in range(8):
        list.append(int(random.random() * 10))
    return list

if __name__ == '__main__':
    for i in range(3):
        list1 = listCreater()
        print(list1)
        print(newtherlandsSort(list1))

运行结果:

[7, 5, 7, 1, 8, 8, 4, 5]
[4, 1, 5, 5, 7, 8, 7, 8]
[6, 6, 0, 0, 6, 1, 0, 9]
[6, 6, 0, 0, 6, 1, 0, 9]
[5, 5, 9, 2, 8, 0, 5, 5]
[2, 0, 5, 5, 5, 5, 9, 8]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值