python实现二分查找与快速排序实例详解


本文摘自php中文网,作者黄舟,侵删。

本文通过实例代码给大家详细介绍了python 二分查找和快速排序,的相关知识,需要的朋友可以参考下

思想简单,细节颇多;本以为很简单的两个小程序,写起来发现bug频出,留此纪念。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

#usr/bin/env python

def binary_search(lst,t):

  low=0

  height=len(lst)-1

  quicksort(lst,0,height)

  print lst

  while low<=height:

    mid = (low+height)/2

    if lst[mid] == t:

      return lst[mid]

    elif lst[mid]>t:

      height=mid-1

    else:

      low=mid+1

  return -1

def quicksort( lst, left , right):

  low=left

  high=right

  key=lst[left]

  if left>=right:

    return 0

  while low<high:

    while low<high and key<lst[high]:

      high=high-1

    lst[low]=lst[high]

    while low<high and key>lst[low]:

      print lst[low]

      low=low+1

    lst[high]=lst[low]

    lst[low]=key

  quicksort( lst , left ,low-1)

  quicksort( lst , low+1 , right)

if __name__=='__main__':

  print binary_search([4,8,1,5,10,2,12,3,6,9],4)

总结

以上就是python实现二分查找与快速排序实例详解的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python开发安卓app可行吗

Python中你必须了解的知识

Python 如何自定义模块?

Python数据采集--beautifulsoup的使用

Python如何判断是不是回文数

Python的序列之列表的通用方法

Python pop函数的定义及使用方式(实例展示)

装了anaconda要卸载Python

Python中n是什么意思?

Python gui编程(tkinter)是什么?实例展示Python tkinter教程

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...