Python 常用排序Demo|冒、插、快、希等入门算法
Python实现日常排序Demo
冒泡排序
import random
lists = random.sample(range(0, 100), 10)
print("冒泡排序".center(20, "-"))
def Bubble_Sort(lists=lists):
# 冒泡排序
count = len(lists)
for i in range(0, count):
for j in range(i + 1, count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
print(lists)
Bubble_Sort()
插入排序
print("插入排序".center(20, "-"))
def Insertion_sort(lists=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
print(lists)
Insertion_sort()
选择排序
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
print("选择排序".center(20, "-"))
def Select_sort(lists=lists):
# 选择排序
count = len(lists)
for i in range(0, count):
min = i
for j in range(i + 1, count):
if lists[min] > lists[j]:
min = j
lists[min], lists[i] = lists[i], lists[min]
print(lists)
Select_sort()
快速排序
print("快速排序".center(20, "-"))
def Quick_sort(lists=lists, left=0, right=len(lists) - 1):
# 快速排序
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
Quick_sort(lists, low, left - 1)
Quick_sort(lists, left + 1, high)
return lists
print(Quick_sort())
快速排序 | lambda
print("快速排序 | lambda".center(20, "-"))
quick_sort = lambda lists : ( (len(lists) <= 1 and [lists]) or [ quick_sort( [x for x in lists[1:] if x < lists[0]] ) + [lists[0]] + quick_sort( [x for x in lists[1:] if x >= lists[0]] ) ] )[0]
print(quick_sort(lists))
希尔排序
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
print("希尔排序".center(20, "-"))
def Shell_sort(lists=lists):
step = len(lists) // 2
while step > 0:
for i in range(step, len(lists)):
while(i >= step and lists[i] < lists[i-step]):
lists[i],lists[i-step] = lists[i-step],lists[i]
i -= step
step //= 2
print(lists)
Shell_sort()
计数排序
print("计数排序".center(20, "-"))
def Count_sort(lists=lists):
n = len(lists)
restful= [None] * n
for i in range(n):
p = 0
for j in range(n):
if lists[i] > lists[j]:
p += 1
restful[p] = lists[i]
print(restful)
Count_sort()
桶排序
'''
Python学习交流,免费公开课,免费资料,
免费答疑,系统学习加QQ群:579817333
'''
print("桶排序".center(20, "-"))
def Bucket_sort(lists=lists, restful=[]):
# 桶排序
buckets = [0] * ((max(lists) - min(lists)) + 1)
for i in range(len(lists)):
buckets[lists[i] - min(lists)] += 1
for i in range(len(buckets)):
if buckets[i] != 0:
restful += [i + min(lists)] * buckets[i]
print(restful)
Bucket_sort()
基数排序
print("基数排序".center(20, "-"))
def Radix_sort(lists=lists):
step = len(lists) // 3
for k in range(step):
radix = [[] for v in range(10)]
for v in lists:
radix[v // (10**k) % 10].append(v)
lists=[j for v in radix for j in v]
print(lists)
Radix_sort()