python写算法快吗,Python实现常见算法

1. 选择排序

import numpy as np

def select_sort(arr):

lenght = len(arr)

for i in range(lenght - 1):

# 假设最小值索引为 minindex

minindex = i

for j in range(i + 1, lenght):

if arr[j] < arr[minindex]:

# 如果最小值后面的元素有比minindex对应的值还要小,就重新设置最小值索引

minindex = j

# 一遍循环下来后,将最新的最小值与之前假设的最小值交换位置

arr[i], arr[minindex] = arr[minindex], arr[i]

return arr

nums = np.random.randint(0,100,size=20,dtype=np.int)

print(nums)

select_sort(nums)

2. 冒泡排序

import numpy as np

def bubble_sort(arr):

length = len(arr)

for i in range(length - 1):

for j in range(length - i - 1):

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

arr[j],arr[j+1] = arr[j+1],arr[j]

return arr

nums = np.random.randint(0,100,size=20,dtype=np.int)

print(nums)

bubble_sort(nums)

3. 插入排序

import numpy as np

def insert_sort(arr):

length = len(arr)

for i in range(1,length):

section_index = i

while section_index >0 and arr[section_index] < arr[section_index -1]:

arr[section_index], arr[section_index - 1] = arr[section_index - 1], arr[section_index]

section_index -= 1

return arr

nums = np.array([3,4,2,6,1,7,5,8,0])

print(nums)

insert_sort(nums)

4. 快速排序

import numpy as np

def quick_sort(arr):

length = len(arr)

if length <= 1:

return arr

else:

pivot = arr[-1]

arr = arr[:-1]

lesser, greater = [], []

for section in arr:

if section > pivot:

greater.append(section)

else:

lesser.append(section)

return quick_sort(lesser) +[pivot] + quick_sort(greater)

nums = np.array([3,4,2,6,1,7,5,8,9])

print(nums)

quick_sort(nums)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值