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

yipeiwu_com7年前Python基础

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

#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设计】网站的支持!

相关文章

Python简单进程锁代码实例

先说说线程 在多线程中,为了保证共享资源的正确性,我们常常会用到线程同步技术. 将一些敏感操作变成原子操作,保证同一时刻多个线程中只有一个线程在执行这个原子操作。 我最常用的是互斥锁,也...

python定时执行指定函数的方法

本文实例讲述了python定时执行指定函数的方法。分享给大家供大家参考。具体实现方法如下: # time a function using time.time() and the a...

Python倒排索引之查找包含某主题或单词的文件

Python倒排索引之查找包含某主题或单词的文件

什么是倒排索引? 倒排索引(英语:Inverted index),也常被称为反向索引、置入档案或反向档案,是一种索引方法,被用来存储在全文搜索下某个单词在一个文档或者一组文档中的存储位置...

python按修改时间顺序排列文件的实例代码

python按修改时间顺序排列文件,具体代码如下所示: import os def sort_file_by_time(file_path): files = os.listdi...

tensorflow实现加载mnist数据集

tensorflow实现加载mnist数据集

mnist作为最基础的图片数据集,在以后的cnn,rnn任务中都会用到 import numpy as np import tensorflow as tf import matpl...