zoukankan      html  css  js  c++  java
  • python 常见排序实例

    使用Python 基础排序算法设计,冒泡排序,插入排序,快速排序...

    需求

    对一组无序数据进行排序算法设计,要求如下:

    输入:[1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]

    输出:[1, 3, 5, 5, 22, 23, 34, 34, 37, 74, 75, 86, 456]

    冒泡排序

    核心算法:循环比较相邻的两个元素,如果前面一个元素比后面一个元素大,则交换位置。

    #!/usr/bin/env python 
    # -*- coding: utf-8 -*-
    
    
    def bubble_sort(data_source):
        length = len(data_source)
        for i in range(1, length):
            for j in range(length - i):
                if data_source[j] > data_source[j + 1]:
                    data_source[j], data_source[j + 1] = data_source[j + 1], data_source[j]
        return data_source
    
    
    if __name__ == '__main__':
        test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
        print bubble_sort(test_array)

    插入排序

    核心算法:从头到尾循环,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入,因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

    #!/usr/bin/env python 
    # -*- coding: utf-8 -*-
    
    
    def insert_sort(data_source):
        count = len(data_source)
        for i in range(1, count):
            key = data_source[i]
            j = i - 1
            while j >= 0:
                if data_source[j] > key:
                    data_source[j], data_source[j + 1] = key, data_source[j]
                j -= 1
        return data_source
    
    if __name__ == '__main__':
        test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
        print insert_sort(test_array)

     快速排序

    核心算法:每次循环,取一个基数,将序列分成三部分:比基数小的数序列,基数,比基数大的序列。不断重复对每个序列进行相同的处理,直到每个序列为空,则完成排序

    #!/usr/bin/env python 
    # -*- coding: utf-8 -*-
    
    
    def quick_sort(data_source):
        length = len(data_source)
        if length == 0:
            return []
        else:
            left = []
            right = []
            for i in range(1, length):
                if data_source[0] > data_source[i]:
                    left.append(data_source[i])
                else:
                    right.append(data_source[i])
            return quick_sort(left) + [data_source[0]] + quick_sort(right)
    
    if __name__ == '__main__':
        test_array = [1, 3, 5, 23, 75, 34, 456, 86, 22, 74, 37, 5, 34]
        print quick_sort(test_array)
    

      

  • 相关阅读:
    UI第十七讲.图片异步加载(包括第三方), KVO, KVC
    第二十一讲.UICollectionView(集合视图)以及瀑布流效果, 通知中心(NSNotificationCenter).
    UI第十九讲:数据库
    UI第十八讲.初级数据持久化 (沙盒, 简单写入对象, 归解档, NSUserDefaults写入读取文件 )
    第十四讲(下) 可视化方式的实现通讯录.(及storyboard方式)
    第十六讲.网络编程 (HTTP协议)
    wslgit
    MyBatis时间比较
    layer开启与关闭加载层
    MyBatis中choose when正确写法
  • 原文地址:https://www.cnblogs.com/guanfuchang/p/5896754.html
Copyright © 2011-2022 走看看