Home > Backend Development > Python Tutorial > Detailed explanation of binary search and quick sorting examples in Python

Detailed explanation of binary search and quick sorting examples in Python

黄舟
Release: 2017-10-14 10:23:37
Original
2437 people have browsed it

This article introduces the relevant knowledge of python binary search and quick sorting in detail through example code. Friends in need can refer to it

The idea is simple and there are many details; two small things that I thought were very simple Program, I found bugs frequently while writing it, so I keep this as a souvenir.


#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__==&#39;__main__&#39;:
  print binary_search([4,8,1,5,10,2,12,3,6,9],4)
Copy after login

Summary

The above is the detailed content of Detailed explanation of binary search and quick sorting examples in Python. For more information, please follow other related articles on the PHP Chinese website!

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