python實現基本算法

1. 冒泡排序

本文采用兩種方法進行冒泡排序,

第一種:第一次排序後,數組中的第一個元素最小

def bubble_sort(lists):
    # 冒泡排序
    count = len(lists)
    for i in range(count):
        for j in range(i + 1, count):
            if lists[i] > lists[j]:
                lists[i], lists[j] = lists[j], lists[i]

a = [7, 4, 9, 10]
bubble_sort(a)
print a

 

第二種:第一次排序後,數組中的最後一個元素最大

def bubble_sort(List):
    for i in range(len(List)-1):
        for j in range(1, len(List)-i):
            if List[j-1] > List[j]:
                List[j-1], List[j] = List[j], List[j-1]

if __name__ == '__main__':
    a = [15,1,9,3,6,8,12,2,0]
    bubble_sort(a)
    print a

 output:

[0, 1, 2, 3, 6, 8, 9, 12, 15]

2.插入排序

def insertSort(num):
    for i in range(1, len(num)):
        key = num[i]
        j = i - 1
        while j >= 0:
            if num[j] > key:
                num[j+1] = num[j]
                num[j] = key
            j -= 1

a = [2, 7, 5, 4]
insertSort(a)
print a

3.快速排序

def quickSort(arr):
        less = []
        pivotList = []
        more = []
        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            for i in arr:
                if i < pivot:
                    less.append(i)
                elif i > pivot:
                    more.append(i)
                else:
                    pivotList.append(i)

            less = quickSort(less)
            more = quickSort(more)
            return less + pivotList + more
a = [5,8,4,7,9,2]
b = quickSort(a)
print a
print b

output:

[5, 8, 4, 7, 9, 2]
[2, 4, 5, 7, 8, 9]

4.二分查找

4.1 打印出所查找值的index

def binary_search(List, t):
    if not List:
        return

    right = len(List) - 1
    left = 0
    while left <= right:
        middle = (right + left) / 2
        print "middle value is " + str(List[middle])
        if List[middle] > t:
            right = middle - 1
        elif List[middle] < t:
            left = middle + 1
        else:
            return middle


if __name__ == '__main__':
    a = [1, 3, 5, 6, 10, 12, 13, 18, 20, 22]
    index = binary_search(a, 6)
    print "This index of 6 is %s" % str(index)

output:

middle value is 10
middle value is 3
middle value is 5
middle value is 6
This index of 6 is 3

4.2 返回是否可以在數組中找到該值

def binary_search(List, t):
    if not List:
        return

    while len(List)/2:
        middle = len(List)/2
        if List[middle] > t:
           List = List[:middle]
        elif List[middle] < t:
           List = List[middle:]
        else:
          return True

    if List[0] == t:
        return True

if __name__ == '__main__':
    a = [1, 3, 5, 6, 10, 12, 13, 18, 20, 22]
    result = binary_search(a, 13)
    print result

output: True

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章