书摘技术干货

《算法图解》书摘-算法介绍/选择排序

2017-06-22  本文已影响34人  GhostStories

欢迎访问我的博客:http://wangnan.tech

第一章 算法介绍

二分查找Python代码

def binary_search(list,item):
    low = 0
    high = len(list-1)
    
    while low <= high:
        mid =(low+high)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid -1
        else:
            low = mid + 1
        return None    

小结

第二章 选择排序

|数组 |链表

---|---|---
读取 | o(1)|o(n)
输入 | o(n)|o(1)
删除|o(n)|o(1)

  def findSmallest(arr):
      smallest = arr[0]
      smallest_index = 0
      for i in range(1,len(arr)):
          if arr[i] < smallest;
              smallest = arr[i]
              smallest_index = i
      return smallest_index
    
  def selectionSort(arr):
   newArr = []
   for i in range(len(arr)):
      smallest = findSmallest(arr)
      newArr.append(arr.pop(smallest))
  return newArr    

小结

上一篇 下一篇

猜你喜欢

热点阅读