Home > Backend Development > Python Tutorial > python快速查找算法应用实例

python快速查找算法应用实例

WBOY
Release: 2016-06-06 11:32:50
Original
1262 people have browsed it

本文实例讲述了Python快速查找算法的应用,分享给大家供大家参考。

具体实现方法如下:

import random
def partition(list_object,start,end):
  random_choice = start
  #random.choice(range(start,end+1))
  #把这里的start改成random()效率会更高些
  x = list_object[random_choice]
  i = start
  j = end
  while True:
    while list_object[i] < x and i < end:
      i += 1
    while list_object[j] > x:
      j -= 1
    if i >= j:
      break
    list_object[i],list_object[j] = list_object[j],list_object[i]
  print list_object
  #list_object[random_choice] = list_object[j]
  #list_object[j] = random_choice
  return j

def quick_sort(list_object,start,end):
  if start < end:
    temp = partition(list_object,start,end)
    quick_sort(list_object,start,temp-1)
    quick_sort(list_object,temp + 1 ,end)
    
a_list = [69,65,90,37,92,6,28,54]
quick_sort(a_list,0,7)
print a_list

Copy after login

程序测试环境为Python2.7.6

输出结果如下:

[54, 65, 28, 37, 6, 69, 92, 90]
[6, 37, 28, 54, 65, 69, 92, 90]
[6, 37, 28, 54, 65, 69, 92, 90]
[6, 28, 37, 54, 65, 69, 92, 90]
[6, 28, 37, 54, 65, 69, 90, 92]
[6, 28, 37, 54, 65, 69, 90, 92]

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template