这几个排序算法写起来都比较简单QAQ
一、冒泡排序
两层for循环就写好了
注意:因为是j和j+1比,所以j的范围是[0,len(nums)-i-1)
def bubble_sort(self,nums):
for i in range(len(nums)):
for j in range(0,len(nums)-i-1,1):
if nums[j]>nums[j+1]:
nums[j],nums[j+1] = nums[j+1],nums[j]
return nums
二、选择排序
# 选择排序
def select_sort(self,nums):
for i in range(len(nums)):
tmp = nums[i]
index = i
for j in range(i+1,len(nums),1):
if nums[j]<tmp:
tmp = nums[j]
index = j
nums[index] = nums[i]
nums[i] = tmp
# print(nums)
return nums
三、插入排序
# 插入排序
def insert_sort(self,nums):
for i in range(1,len(nums),1):
tmp = nums[i]
j = i-1
while j>=0:
if tmp>nums[j]:
break
else:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = tmp
# print(nums)
return nums
四、归并排序
# 归并排序
# 对两个数组进行归并
def merge(self,num1,num2):
r = []
i = 0
j = 0
while i<len(num1) and j<len(num2):
if num1[i]<=num2[j]:
r.append(num1[i])
i += 1
elif num1[i]>num2[j]:
r.append(num2[j])
j += 1
if i==len(num1) and j<len(num2):
r.extend(num2[j:])
if i<len(num1) and j==len(num2):
r.extend(num1[i:])
print(r)
return r
# 递归
def merge_sort(self,nums):
if len(nums)<=1:
return nums
a = int(len(nums)//2)
# print(a)
left = self.merge_sort(nums[:a])
right = self.merge_sort(nums[a:])
return self.merge(left,right)
*自己写给自己看的博客
*文章内容不保证正确
*部分内容来源于网络,侵删
今天也是元气满满的一天哦~~
冲鸭~~QWQ