Python quickly finds examples of algorithm applications

  • 2020-04-02 14:11:01
  • OfStack

This article illustrates the application of Python quick search algorithm, and shares it with you for your reference.

The specific implementation method is as follows:


import random
def partition(list_object,start,end):
  random_choice = start
  #random.choice(range(start,end+1))
  # Put here start to random() It will be more efficient 
  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

The program test environment was Python2.7.6

The output results are as follows:


[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]

I hope this article has helped you with your Python programming.


Related articles: