几个简单的算法

一、  二分查找

二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

# __Author__:oliver
# __DATE__:2/19/17
class Binary_Search(object):
    def __init__(self, data_list):
        self.data_list = data_list
        self.begin = 0  # 开始位置的索引
        self.end = len(data_list) - 1  # 结束位置的索引
        self.middle = 0

    def find(self, num):
        self.middle = (self.begin + self.end) // 2  # 中间位置的索引
        if num < self.data_list[self.middle]:
            self.end = self.middle - 1
        elif num > self.data_list[self.middle]:
            self.begin = self.middle + 1
        else:
            return [num, self.middle]
        if self.begin > self.end:
            return 0
        return self.find(num)


def main(data_list, num):
    binary_search = Binary_Search(data_list)
    result = binary_search.find(num)
    print('%s was found,the index for %s' % (result[0], result[1])) if result else print("Not Found.")


if __name__ == '__main__':
    data_list = [1, 3, 23, 50, 88, 91, 107, 200, 201]
    while 1:
        num = input("Please enter the number you want to find (e)Exit:").strip()
        if num == "e":
            break
        main(data_list, int(num))

二、  Python自带排序方法

 

三、  侏儒排序法

def gnomesort(data_list):
    i = 0
    while i < len(data_list):
        if i == 0 or data_list[i-1] <= data_list[i]:
            i += 1
        else:
            data_list[i],data_list[i-1] = data_list[i-1],data_list[i]
            i -= 1


if __name__ == '__main__':
    data_list = [8, 10, 9, 6, 4, 16, 5, 13, 26, 18, 2, 45, 34, 23, 1, 7, 3]
    print(data_list)
    gnomesort(data_list)
    print(data_list)

四、  归并排序法

def mergesort(data_list):
    mid = len(data_list) // 2
    lft,rgt = data_list[:mid],data_list[mid:]
    if len(lft) > 1: lft = mergesort(lft)
    if len(rgt) > 1: rgt = mergesort(rgt)
    result = []
    while lft and rgt:
        if lft[-1] >= rgt[-1]:
            result.append(lft.pop())
        else:
            result.append(rgt.pop())
    result.reverse()
    return (lft or rgt) + result


if __name__ == '__main__':
    data_list = [8, 10, 9, 6, 4, 16, 5, 13, 26, 18, 2, 45, 34, 23, 1, 7, 3]
    print(data_list)
    res = mergesort(data_list)
    print(res)

 

 

 

 

 

posted on 2017-02-19 14:01  oliver.lee  阅读(368)  评论(0编辑  收藏  举报

导航