jtahstu的博客

root@jtahstu.com   Github   英文博客  

最新碎语:以后没事写写小的知识点吧

您的位置:jtahstu的博客 >算法> 数据结构与算法从入门到懵逼 - 排序算法(Python实现)

数据结构与算法从入门到懵逼 - 排序算法(Python实现)

插入排序

# 插入排序
# 在前i个元素都是有序的情况下,将第i+1个元素插入进去
def insertSort(lists):
    count = len(lists)
    for i in range(1, count):
        key = lists[i]
        j = i - 1
        while j >= 0:
            if (lists[j] > key):
                lists[j + 1] = lists[j]
                lists[j] = key
            j -= 1
    return lists

list = [5, 4, 7, 8, 9, 1, 2, 3, 6]
insertSort(list)
print(list)

list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
insertSort(list2)

list3 = [9, 8, 7, 6, 5, 4, 3, 2, 1]
insertSort(list3)

冒泡排序

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

list = [5, 4, 7, 8, 9, 1, 2, 3, 6]
BubbleSort(list)
print(list)

list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
BubbleSort(list2)
print(list2)

list3 = [9, 8, 7, 6, 5, 4, 3, 2, 1]
BubbleSort(list3)
print(list3)

快速排序


"""
@author: jtusta
@license: MIT Licence 
@contact: root@jtahstu.com
@site: www.jtahstu.com
@software: PyCharm Community Edition
@file: quickSort.py
@time: 2017/01/05 22:22
"""
# 快速排序
def quickSort(lists, left, right):
    if left >= right:
        return lists
    key = lists[left]
    low = left
    high = right
    while left < right:
        while left < right and lists[right] >= key:
            right -= 1
        lists[left] = lists[right]
        while left < right and lists[left] <= key:
            left += 1
        lists[right] = lists[left]
    lists[right] = key
    quickSort(lists, low, left - 1)
    quickSort(lists, left + 1, high)
    return lists

list = [5, 4, 7, 8, 9, 1, 2, 3, 6]
quickSort(list)
print(list)

list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
quickSort(list2)
print(list2)

list3 = [9, 8, 7, 6, 5, 4, 3, 2, 1]
quickSort(list3)
print(list3)
//后续继续更新


---

本文章采用 知识共享署名2.5中国大陆许可协议 进行许可,欢迎转载,演绎或用于商业目的。

---

二维码加载中...

扫一扫移动端访问O(∩_∩)O

发表评论

26 + 15 =
路人甲 表情
看不清楚?点图切换 Ctrl+Enter快速提交
正在加载中……