python几种排序算法_python:4种基本排序算法

1.冒泡排序

# -*- coding:utf-8 -*-

def bubble_sort(A):

for i in range(len(A)-1): # 决定进行的轮数

for j in range(0, len(A)-i-1): # 列表下标

if A[j] > A[j+1]:

A[j+1], A[j] = A[j], A[j+1]

return A

A = [0, 5, 4, 3, 2, 1]

print(bubble_sort(A))

2.快速排序

# -*- coding:utf-8 -*-

def partition(A, low, high):

pivot = A[low]

while low < high:

while low < high and A[high] >= pivot:

high -= 1

A[low] = A[high]

while low < high and A[low] <= pivot:

low += 1

A[high] = A[low]

A[low] = pivot

return low

def quick_sort(A, low, high):

if low < high:

pivot = partition(A, low, high)

print(A, low, high)

quick_sort(A, low, pivot-1)

quick_sort(A, pivot+1, high)

return A

A = [3, 5, 4, 8, 2, 1]

print(quick_sort(A, 0, 5))

3.归并排序

# -*- coding:utf-8 -*-

def merge_sort(A):

if len(A) == 1:

return A

mid = len(A)//2

left = merge_sort(A[:mid])

right = merge_sort(A[mid:])

return merge(left, right)

def merge(left, right):

result = []

while len(left) > 0 and len(right) > 0:

if left[0] < right[0]:

result.append(left.pop(0))

else:

result.append(right.pop(0))

result += left

result += right

return result

A = [3, 5, 4, 8, 2, 1]

print(merge_sort(A))

4. 插入排序

# -*- coding:utf-8 -*-

def insert_sort(A):

for i in range(1, len(A)):

j = i-1

if A[i] < A[j]:

temp = A[i]

A[i] = A[j]

j = j-1

while j >= 0 and A[j] > temp:

A[j+1] = A[j]

j -= 1

A[j+1] = temp

return A

A = [3, 5, 4, 8, 2, 1]

print(insert_sort(A))

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值